torrent._pike
Go to the documentation of this file.
1 /*0*/
2 inherit Service.Service;
3 #include <events.h>
4 class torrent {
5 public:
6 
7 
8  object updater;
9 
10 void send_update(object obj, int id, string func, void|mixed args)
11 {
12  if ( !arrayp(args) )
13  args = ({ id });
14  else
15  args = ({ id }) + args;
16 
17  send_cmd(obj, func, args, 1); // do not wait
18 }
19 
20 void download(int id, string meta)
21 {
22  Stdio.File f = Stdio.File("torrent/"+id+".torrent", "wct");
23  f->write(meta);
24  f->close();
25  Protocols.Bittorrent.Torrent t=Protocols.Bittorrent.Torrent();
26  t->downloads_update_status = lambda() {
27  send_update(updater, id, "downloads_update_status");
28  };
29 
30  // Callback when pieces status change (when we get new stuff): //
31  t->pieces_update_status = lambda() {
32  send_update(updater, id, "piece_update");
33  };
34 
35  // Callback when peer status changes (connect, disconnect, choked...): //
36  t->peer_update_status = lambda() {
37  send_update(updater, id, "peer_update");
38  };
39 
40  // Callback when download is completed:
41  t->download_completed_callback= lambda() {
42  send_update(updater, id, "finished");
43  };
44  t->warning = lambda() {
45  send_update(updater, id, "warn");
46  };
47 
48  // Initiate targets from Torrent,
49  // if target was created, no need to verify:
50  write("Checking existing file:");
51  function progress = lambda() {
52  send_update(updater, id, "progress");
53  };
54 
55  if (t->fix_targets(1,0,progress)==1)
56  t->verify_targets(progress);
57 
58  // Open port to listen on,
59  // we want to do this to be able to talk to firewalled peers:
60  t->my_port=6800;
61  t->open_port();
62 
63  // Ok, start calling tracker to get peers,
64  // and tell about us:
65  t->start_update_tracker();
66  t->start_download();
67 }
68 
69 
70 
71 void notify(mixed args)
72 {
73 }
74 
75 void call_service(mixed args)
76 {
77  switch(args[0]) {
78  case "download":
79  download(args[1], args[2]);
80  break;
81  case "run":
82  updater = args[1];
83  load_torrents();
84  break;
85  }
86 }
87 
88 protected:
89  void load_torrents()
90 {
91  if ( !Stdio.exist("torrents") )
92  mkdir("torrents");
93  // read all torrents in torrents/
94  foreach(get_dir("torrents"), string fname) {
95  int id;
96  Stdio.File f = Stdio.File("torrents/"+fname, "r");
97  string meta = f->read();
98  f->close();
99  if ( sscanf(fname, "%d.torrent", id) )
100  download(id, meta);
101  }
102 
103 }
104 
105 public:
106 
107 protected:
108  void run()
109 {
110 }
111 
112 public:
113 
114 int main(int argc, array argv)
115 {
116  init( "torrent", argv );
117  start();
118  return -17;
119 }
120 
121 
122 };