system.js 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579
  1. // Current system global object
  2. var system = {
  3. version: "1.6.1",
  4. rootPath: "tr-web-control/",
  5. codeupdate: "20200913",
  6. configHead: "transmission-web-control",
  7. // default config, can be customized in config.js
  8. config: {
  9. autoReload: true,
  10. reloadStep: 5000,
  11. pageSize: 30,
  12. pagination: true,
  13. pageList: [10, 20, 30, 40, 50, 100, 150, 200, 250, 300, 5000],
  14. defaultSelectNode: null,
  15. autoExpandAttribute: false,
  16. defaultLang: "",
  17. foldersShow: false,
  18. // theme
  19. theme: "default",
  20. // 是否显示BT服务器
  21. showBTServers: false,
  22. // ipinfo.io token
  23. ipInfoToken: '',
  24. ipInfoFlagUrl: '',
  25. ipInfoDetailUrl: '',
  26. ui: {
  27. status: {
  28. tree: {},
  29. layout: {
  30. main: {},
  31. body: {},
  32. left: {}
  33. },
  34. panel: {},
  35. size: {
  36. nav: {},
  37. attribute: {}
  38. }
  39. }
  40. },
  41. hideSubfolders: false,
  42. simpleCheckMode: false,
  43. nav: {
  44. servers: true,
  45. folders: true,
  46. statistics: true,
  47. labels: false
  48. },
  49. labels: [],
  50. labelMaps: {},
  51. ignoreVersion: []
  52. },
  53. storageKeys: {
  54. dictionary: {
  55. folders: "dictionary.folders"
  56. }
  57. },
  58. // Local data storage
  59. dictionary: {
  60. folders: null
  61. },
  62. checkUpdateScript: "https://api.github.com/repos/ronggang/transmission-web-control/releases/latest",
  63. contextMenus: {},
  64. panel: null,
  65. lang: null,
  66. reloading: false,
  67. autoReloadTimer: null,
  68. downloadDir: "",
  69. islocal: false,
  70. B64: new Base64(),
  71. // The currently selected torrent number
  72. currentTorrentId: 0,
  73. flags: [],
  74. ipdetail: [],
  75. control: {
  76. tree: null,
  77. torrentlist: null
  78. },
  79. userConfig: {
  80. torrentList: {
  81. fields: [],
  82. sortName: null,
  83. sortOrder: "asc"
  84. }
  85. },
  86. serverConfig: null,
  87. serverSessionStats: null,
  88. // Dialog Templates Temporary list
  89. templates: {},
  90. // 当前已选中的行
  91. checkedRows: [],
  92. uiIsInitialized: false,
  93. popoverCount: 0,
  94. // 当前数据目录,用于添加任务的快速保存路径选择
  95. currentListDir: "",
  96. /**
  97. * 设置语言
  98. */
  99. setlang: function (lang, callback) {
  100. // If no language is specified, acquires the current browser default language
  101. if (!lang) {
  102. if (this.config.defaultLang)
  103. lang = this.config.defaultLang;
  104. else
  105. lang = navigator.language || navigator.browserLanguage;
  106. //this.debug("lang",lang);
  107. }
  108. if (!lang) lang = "zh-CN";
  109. // If - contains the language code, you need to turn the second half to uppercase
  110. if (lang.indexOf("-") != -1) {
  111. // Because Linux file size restrictions
  112. lang = lang.split("-")[0].toLocaleLowerCase() + "-" + lang.split("-")[1].toLocaleUpperCase();
  113. }
  114. // If the language pack is not defined, English is used
  115. if (!this.languages[lang]) {
  116. lang = "en";
  117. }
  118. // 统一使用 _ 替代 -
  119. lang = lang.replace("-", "_");
  120. $.getJSON(system.rootPath + "i18n/" + lang + ".json", function (result) {
  121. if (result) {
  122. system.lang = $.extend(true, system.defaultLang, result);
  123. }
  124. system.resetLangText();
  125. // Set the easyui language
  126. $.getScript(system.rootPath + "script/easyui/locale/easyui-lang-" + lang + ".js")
  127. .done(function (script, textStatus) {
  128. if (callback)
  129. callback();
  130. // If the loading fails, the English language is loaded
  131. })
  132. .fail(function (jqxhr, settings, exception) {
  133. $.getScript(system.rootPath + "script/easyui/locale/easyui-lang-en.js", function () {
  134. if (callback)
  135. callback();
  136. });
  137. });
  138. });
  139. },
  140. /**
  141. * 程序初始化
  142. */
  143. init: function (lang, islocal, devicetype) {
  144. this.readConfig();
  145. this.lastUIStatus = JSON.parse(JSON.stringify(this.config.ui.status));
  146. this.islocal = (islocal == 1 ? true : false);
  147. this.panel = {
  148. main: $("#main"),
  149. top: $("#m_top"),
  150. toolbar: $("#m_toolbar"),
  151. left_layout: $("#m_left_layout"),
  152. left: $("#m_left"),
  153. body: $("#m_body"),
  154. layout_body: $("#layout_body"),
  155. layout_left: $("#layout_left"),
  156. list: $("#m_list"),
  157. attribute: $("#m_attribute"),
  158. bottom: $("#m_bottom"),
  159. title: $("#m_title"),
  160. status: $("#m_status"),
  161. statusbar: $("#m_statusbar"),
  162. status_text: $("#status_text"),
  163. droparea: $("#dropArea")
  164. };
  165. if (this.lang == null) {
  166. this.setlang(lang, function () {
  167. system.initdata()
  168. });
  169. } else {
  170. this.initdata();
  171. }
  172. this.initThemes();
  173. // 剪切板组件
  174. this.clipboard = new ClipboardJS('#toolbar_copyPath');
  175. },
  176. // Set the language information
  177. resetLangText: function (parent) {
  178. if (!parent)
  179. parent = $;
  180. var items = parent.find("*[system-lang]");
  181. $.each(items, function (key, item) {
  182. var name = $(item).attr("system-lang");
  183. if (name.substr(0, 1) == "[") {
  184. $(item).html(eval("system.lang" + name));
  185. } else {
  186. $(item).html(eval("system.lang." + name));
  187. }
  188. });
  189. items = parent.find("*[system-tip-lang]");
  190. $.each(items, function (key, item) {
  191. var name = $(item).attr("system-tip-lang");
  192. if (name.substr(0, 1) == "[") {
  193. $(item).attr("title", eval("system.lang" + name));
  194. } else {
  195. $(item).attr("title", eval("system.lang." + name));
  196. }
  197. });
  198. },
  199. initdata: function () {
  200. //this.panel.title.text(this.lang.system.title+" "+this.version+" ("+this.codeupdate+")");
  201. $(document).attr("title", this.lang.system.title + " " + this.version);
  202. // 设置开关组件默认文字
  203. $.fn.switchbutton.defaults.onText = this.lang["public"]["text-on"];
  204. $.fn.switchbutton.defaults.offText = this.lang["public"]["text-off"];
  205. // The initial navigation bar
  206. var buttons = new Array();
  207. var title = "<span>" + this.lang.title.left + "</span>";
  208. // 暂时取消导航栏上的额外按钮
  209. // buttons.push("<span class='tree-title-toolbar'>");
  210. // for (var key in this.lang.tree.toolbar.nav) {
  211. // var value = this.lang.tree.toolbar.nav[key];
  212. // buttons.push('<a href="javascript:void(0);" id="tree-toolbar-nav-' + key + '" class="easyui-linkbutton" data-options="plain:true,iconCls:\'icon-disabled\'" onclick="javascript:system.navToolbarClick(this);">' + value + "</a>");
  213. // }
  214. // buttons.push("</span>");
  215. if (buttons.length > 1) {
  216. title += buttons.join("");
  217. this.panel.left_layout.panel("setTitle", title);
  218. for (var key in this.lang.tree.toolbar.nav) {
  219. $("#tree-toolbar-nav-" + key).linkbutton();
  220. switch (key) {
  221. case "folders":
  222. if (system.config.foldersShow) {
  223. $("tree-toolbar-nav-" + key).linkbutton({
  224. iconCls: "icon-enabled"
  225. }).data("status", 1);
  226. } else {
  227. $("tree-toolbar-nav-" + key).linkbutton({
  228. iconCls: "icon-disabled"
  229. }).data("status", 0);
  230. }
  231. break;
  232. default:
  233. break;
  234. }
  235. }
  236. } else {
  237. this.panel.left_layout.panel("setTitle", title);
  238. }
  239. // Initialize the torrent list column title
  240. title = "<span>" + this.lang.title.list + "</span>";
  241. buttons.length = 0;
  242. // buttons.push("<span class='tree-title-toolbar'>");
  243. // for (var key in this.lang["torrent-head"].buttons) {
  244. // var value = this.lang["torrent-head"].buttons[key];
  245. // buttons.push('<a href="javascript:void(0);" id="torrent-head-buttons-' + key + '" class="easyui-linkbutton" data-options="plain:true,iconCls:\'icon-disabled\'" onclick="javascript:system.navToolbarClick(this);">' + value + "</a>");
  246. // }
  247. // buttons.push("</span>");
  248. if (buttons.length > 1) {
  249. title += buttons.join("");
  250. this.panel.body.panel("setTitle", title);
  251. for (var key in this.lang["torrent-head"].buttons) {
  252. $("#torrent-head-buttons-" + key).linkbutton();
  253. switch (key) {
  254. case "autoExpandAttribute":
  255. if (system.config.autoExpandAttribute) {
  256. $("#torrent-head-buttons-" + key).linkbutton({
  257. iconCls: "icon-enabled"
  258. }).data("status", 1);
  259. } else {
  260. $("#torrent-head-buttons-" + key).linkbutton({
  261. iconCls: "icon-disabled"
  262. }).data("status", 0);
  263. }
  264. break;
  265. default:
  266. break;
  267. }
  268. }
  269. } else {
  270. this.panel.body.panel("setTitle", title);
  271. }
  272. this.panel.status.panel("setTitle", this.lang.title.status);
  273. // 设置属性栏
  274. this.panel.attribute.panel({
  275. title: this.lang.title.attribute,
  276. onExpand: function () {
  277. if (system.currentTorrentId != 0 && $(this).data("isload")) {
  278. system.getTorrentInfos(system.currentTorrentId);
  279. } else {
  280. system.clearTorrentAttribute();
  281. }
  282. },
  283. onLoad: function () {
  284. if (!$(this).data("isload")) {
  285. $(this).data("isload", true);
  286. if (system.currentTorrentId != 0) {
  287. setTimeout(function () {
  288. system.getTorrentInfos(system.currentTorrentId);
  289. }, 500);
  290. }
  291. }
  292. }
  293. });
  294. // Set the language
  295. $.each(this.languages, function (key, value) {
  296. $("<option/>").text(value).val(key).attr("selected", (key == system.lang.name ? true : false)).appendTo(system.panel.top.find("#lang"));
  297. });
  298. this.panel.top.find("#lang").change(function () {
  299. location.href = "?lang=" + this.value;
  300. });
  301. this.panel.toolbar.attr("class", "panel-header");
  302. this.initTree();
  303. this.initToolbar();
  304. this.initStatusBar();
  305. this.initTorrentTable();
  306. this.connect();
  307. this.initEvent();
  308. // Check for updates
  309. this.checkUpdate();
  310. },
  311. /**
  312. * 初始化相关事件
  313. */
  314. initEvent: function () {
  315. // When the window size changes
  316. $(window).resize(function () {
  317. $("#main").layout("resize");
  318. });
  319. // Add file drag-and-drop event handling - Begin
  320. this.panel.droparea[0].addEventListener("dragover", function (e) {
  321. e.stopPropagation();
  322. e.preventDefault();
  323. system.debug("#dropArea.dragover");
  324. }, false);
  325. this.panel.list[0].addEventListener("dragover", function (e) {
  326. e.stopPropagation();
  327. e.preventDefault();
  328. system.panel.droparea.show();
  329. system.debug("dragover");
  330. }, false);
  331. this.panel.droparea[0].addEventListener("drop", function (e) {
  332. e.stopPropagation();
  333. e.preventDefault();
  334. system.panel.droparea.hide();
  335. system.debug("drop.e.dataTransfer:", e.dataTransfer);
  336. system.checkDropFiles(e.dataTransfer.files);
  337. }, false);
  338. this.panel.droparea[0].addEventListener("dragleave", function (e) {
  339. e.stopPropagation();
  340. e.preventDefault();
  341. system.panel.droparea.hide();
  342. system.debug("dragleave");
  343. }, false);
  344. $("#text-drop-title").html(this.lang["public"]["text-drop-title"]);
  345. // End
  346. // 取消选择所有已选中的种子
  347. $("#button-cancel-checked").on("click", function(){
  348. system.control.torrentlist.datagrid("uncheckAll");
  349. });
  350. // 树型目录事件
  351. this.panel.left.tree({
  352. onExpand: function(node) {
  353. system.config.ui.status.tree[node.id] = node.state;
  354. system.saveConfig();
  355. },
  356. onCollapse: function(node) {
  357. system.config.ui.status.tree[node.id] = node.state;
  358. system.saveConfig();
  359. }
  360. });
  361. // 设置属性栏
  362. this.panel.layout_body.layout({
  363. onExpand: function (region) {
  364. system.config.ui.status.layout.body[region] = "open";
  365. system.saveConfig();
  366. },
  367. onCollapse: function(region) {
  368. system.config.ui.status.layout.body[region] = "closed";
  369. system.saveConfig();
  370. }
  371. });
  372. this.panel.layout_left.layout({
  373. onExpand: function (region) {
  374. system.config.ui.status.layout.left[region] = "open";
  375. system.saveConfig();
  376. },
  377. onCollapse: function(region) {
  378. system.config.ui.status.layout.left[region] = "closed";
  379. system.saveConfig();
  380. }
  381. });
  382. this.panel.main.layout({
  383. onExpand: function (region) {
  384. system.config.ui.status.layout.main[region] = "open";
  385. system.saveConfig();
  386. },
  387. onCollapse: function(region) {
  388. system.config.ui.status.layout.main[region] = "closed";
  389. system.saveConfig();
  390. }
  391. });
  392. },
  393. layoutResize: function(target, size) {
  394. if (!system.uiIsInitialized) return;
  395. if (system.config.ui.status.size[target]) {
  396. system.config.ui.status.size[target] = size;
  397. system.saveConfig();
  398. }
  399. },
  400. // Navigation toolbar Click Events
  401. navToolbarClick: function (source) {
  402. var key = source.id;
  403. var status = $(source).data("status");
  404. var treenode = null;
  405. switch (key) {
  406. case "tree-toolbar-nav-folders":
  407. treenode = this.panel.left.tree("find", "folders");
  408. if (status == 1) {
  409. this.config.foldersShow = false;
  410. } else {
  411. this.config.foldersShow = true;
  412. }
  413. break;
  414. case "tree-toolbar-nav-statistics":
  415. treenode = this.panel.left.tree("find", "statistics");
  416. break;
  417. case "torrent-head-buttons-autoExpandAttribute":
  418. treenode = {};
  419. treenode.target = null;
  420. if (status == 1) {
  421. this.config.autoExpandAttribute = false;
  422. } else {
  423. this.config.autoExpandAttribute = true;
  424. }
  425. break;
  426. }
  427. if (!treenode) {
  428. return;
  429. }
  430. if (status == 1) {
  431. $(source).linkbutton({
  432. iconCls: "icon-disabled"
  433. });
  434. $(treenode.target).parent().hide();
  435. status = 0;
  436. } else {
  437. $(source).linkbutton({
  438. iconCls: "icon-enabled"
  439. });
  440. $(treenode.target).parent().show();
  441. status = 1;
  442. }
  443. $(source).data("status", status);
  444. this.saveConfig();
  445. },
  446. // Check the dragged files
  447. checkDropFiles: function (sources) {
  448. if (!sources || !sources.length) return;
  449. var files = new Array();
  450. for (var i = 0; i < sources.length; i++) {
  451. var file = sources[i];
  452. if ((file.name.split(".")).pop().toLowerCase() == "torrent")
  453. files.push(file);
  454. }
  455. if (files.length > 0) {
  456. system.openDialogFromTemplate({
  457. id: "dialog-torrent-addfile",
  458. options: {
  459. title: system.lang.toolbar["add-torrent"],
  460. width: 620,
  461. height: system.config.nav.labels ? 500 : 300,
  462. resizable: true
  463. },
  464. datas: {
  465. "files": files
  466. }
  467. });
  468. }
  469. },
  470. // Initialize the tree list
  471. initTree: function () {
  472. var items = [{
  473. id: "torrent-all",
  474. iconCls: "iconfont tr-icon-home",
  475. text: this.lang.tree.all + " (" + this.lang.tree.status.loading + ")",
  476. children: [{
  477. id: "downloading",
  478. text: this.lang.tree.downloading,
  479. iconCls: "iconfont tr-icon-download"
  480. }, {
  481. id: "paused",
  482. text: this.lang.tree.paused,
  483. iconCls: "iconfont tr-icon-pause2"
  484. }, {
  485. id: "sending",
  486. text: this.lang.tree.sending,
  487. iconCls: "iconfont tr-icon-upload"
  488. }, {
  489. id: "check",
  490. text: this.lang.tree.check,
  491. iconCls: "iconfont tr-icon-data-check"
  492. }, {
  493. id: "actively",
  494. text: this.lang.tree.actively,
  495. iconCls: "iconfont tr-icon-actively"
  496. }, {
  497. id: "error",
  498. text: this.lang.tree.error,
  499. iconCls: "iconfont tr-icon-errors"
  500. }, {
  501. id: "warning",
  502. text: this.lang.tree.warning,
  503. iconCls: "iconfont tr-icon-warning"
  504. }]}
  505. ];
  506. var navContents = {
  507. "servers": {
  508. id: "servers",
  509. text: this.lang.tree.servers,
  510. state: "closed",
  511. iconCls: "iconfont tr-icon-servers",
  512. children: [{
  513. id: "servers-loading",
  514. text: this.lang.tree.status.loading,
  515. iconCls: "tree-loading"
  516. }]
  517. },
  518. "folders": {
  519. id: "folders",
  520. text: this.lang.tree.folders,
  521. iconCls: "iconfont tr-icon-folder",
  522. state: "closed",
  523. children: [{
  524. id: "folders-loading",
  525. text: this.lang.tree.status.loading,
  526. iconCls: "tree-loading"
  527. }]
  528. },
  529. "statistics": {
  530. id: "statistics",
  531. text: this.lang.tree.statistics.title,
  532. state: "closed",
  533. iconCls: "iconfont tr-icon-shuju",
  534. children: [{
  535. id: "cumulative-stats",
  536. text: this.lang.tree.statistics.cumulative,
  537. iconCls: "iconfont tr-icon-folder",
  538. children: [{
  539. id: "uploadedBytes",
  540. text: this.lang.tree.statistics.uploadedBytes,
  541. iconCls: "iconfont tr-icon-empty"
  542. }, {
  543. id: "downloadedBytes",
  544. text: this.lang.tree.statistics.downloadedBytes,
  545. iconCls: "iconfont tr-icon-empty"
  546. }, {
  547. id: "filesAdded",
  548. text: this.lang.tree.statistics.filesAdded,
  549. iconCls: "iconfont tr-icon-empty"
  550. }, {
  551. id: "sessionCount",
  552. text: this.lang.tree.statistics.sessionCount,
  553. iconCls: "iconfont tr-icon-empty"
  554. }, {
  555. id: "secondsActive",
  556. text: this.lang.tree.statistics.secondsActive,
  557. iconCls: "iconfont tr-icon-empty"
  558. }]
  559. }, {
  560. id: "current-stats",
  561. text: this.lang.tree.statistics.current,
  562. iconCls: "iconfont tr-icon-folder",
  563. children: [{
  564. id: "current-uploadedBytes",
  565. text: this.lang.tree.statistics.uploadedBytes,
  566. iconCls: "iconfont tr-icon-empty"
  567. }, {
  568. id: "current-downloadedBytes",
  569. text: this.lang.tree.statistics.downloadedBytes,
  570. iconCls: "iconfont tr-icon-empty"
  571. }, {
  572. id: "current-filesAdded",
  573. text: this.lang.tree.statistics.filesAdded,
  574. iconCls: "iconfont tr-icon-empty"
  575. }, {
  576. id: "current-sessionCount",
  577. text: this.lang.tree.statistics.sessionCount,
  578. iconCls: "iconfont tr-icon-empty"
  579. }, {
  580. id: "current-secondsActive",
  581. text: this.lang.tree.statistics.secondsActive,
  582. iconCls: "iconfont tr-icon-empty"
  583. }]
  584. }]
  585. },
  586. "labels": {
  587. id: "labels",
  588. text: this.lang.tree.labels,
  589. iconCls: "iconfont tr-icon-labels"
  590. }
  591. }
  592. for (var key in this.config.nav) {
  593. var value = this.config.nav[key];
  594. var data = navContents[key];
  595. if (data) {
  596. if (value) {
  597. items.push(data);
  598. }
  599. }
  600. }
  601. this.panel.left.tree({
  602. data: items,
  603. onSelect: function (node) {
  604. system.loadTorrentToList({
  605. node: node
  606. });
  607. system.currentListDir = node.downDir;
  608. },
  609. lines: true
  610. });
  611. },
  612. /**
  613. * 初始化界面状态
  614. */
  615. initUIStatus: function() {
  616. if (this.uiIsInitialized) return;
  617. system.uiIsInitialized = true;
  618. var status = this.lastUIStatus.tree;
  619. for (var key in status) {
  620. var node = this.panel.left.tree("find", key);
  621. if (node && node.target) {
  622. if (status[key]=="open") {
  623. this.panel.left.tree("expand", node.target);
  624. } else {
  625. this.panel.left.tree("collapse", node.target);
  626. }
  627. }
  628. }
  629. // 是否显示数据目录
  630. // if (!this.config.foldersShow) {
  631. // var node = this.panel.left.tree("find", "folders");
  632. // $(node.target).parent().hide();
  633. // }
  634. // node that specifies the default selection
  635. if (this.config.defaultSelectNode) {
  636. var node = this.panel.left.tree("find", this.config.defaultSelectNode);
  637. // 当不显示目录时,如果最后选择的为目录,则显示所有种子;
  638. if (node && (this.config.foldersShow || this.config.defaultSelectNode.indexOf("folders")==-1)) {
  639. this.panel.left.tree("select", node.target);
  640. } else {
  641. node = this.panel.left.tree("find", "torrent-all");
  642. this.panel.left.tree("select", node.target);
  643. }
  644. }
  645. // 恢复尺寸
  646. if (this.lastUIStatus.size.nav && this.lastUIStatus.size.nav.width) {
  647. this.panel.main.layout('panel', 'west').panel('resize', { width: this.lastUIStatus.size.nav.width + 5 });
  648. this.panel.main.layout("resize");
  649. }
  650. if (this.lastUIStatus.size.attribute && this.lastUIStatus.size.attribute.height) {
  651. this.panel.layout_body.layout('panel', 'south').panel('resize', { height: this.lastUIStatus.size.attribute.height });
  652. this.panel.layout_body.layout("resize");
  653. }
  654. // 恢复展开状态
  655. status = this.lastUIStatus.layout.body;
  656. for (var key in status) {
  657. if (status[key]=="open") {
  658. this.panel.layout_body.layout("expand", key);
  659. } else {
  660. this.panel.layout_body.layout("collapse", key);
  661. }
  662. }
  663. status = this.lastUIStatus.layout.left;
  664. for (var key in status) {
  665. if (status[key]=="open") {
  666. this.panel.layout_left.layout("expand", key);
  667. } else {
  668. this.panel.layout_left.layout("collapse", key);
  669. }
  670. }
  671. status = this.lastUIStatus.layout.main;
  672. for (var key in status) {
  673. if (status[key]=="open") {
  674. this.panel.main.layout("expand", key);
  675. } else {
  676. this.panel.main.layout("collapse", key);
  677. }
  678. }
  679. },
  680. // Initialize the torrent list display table
  681. initTorrentTable: function () {
  682. this.control.torrentlist = $("<table/>").attr("class", "torrent-list").appendTo(this.panel.list);
  683. var headContextMenu = null;
  684. var selectedIndex = -1;
  685. $.get(system.rootPath + "template/torrent-fields.json?time=" + (new Date()), function (data) {
  686. var fields = data.fields;
  687. var _fields = {}
  688. for (var i=0;i<fields.length;i++) {
  689. var item = fields[i];
  690. _fields[item.field] = item;
  691. }
  692. if (system.userConfig.torrentList.fields.length != 0) {
  693. fields = $.extend(fields, system.userConfig.torrentList.fields);
  694. }
  695. // User field settings
  696. system.userConfig.torrentList.fields = fields;
  697. for (var key in fields) {
  698. var item = fields[key];
  699. var _field = _fields[item.field];
  700. if (_field && _field["formatter"]) {
  701. item["formatter"] = _field["formatter"];
  702. } else if (item["formatter"]) {
  703. delete item["formatter"];
  704. }
  705. if (_field && _field["sortable"]) {
  706. item["sortable"] = _field["sortable"];
  707. } else if (item["sortable"]) {
  708. delete item["sortable"];
  709. }
  710. item.title = system.lang.torrent.fields[item.field] || item.field;
  711. system.setFieldFormat(item);
  712. }
  713. // 初始化种子列表
  714. system.control.torrentlist.datagrid({
  715. autoRowHeight: false,
  716. pagination: system.config.pagination,
  717. rownumbers: true,
  718. remoteSort: false,
  719. checkOnSelect: false,
  720. pageSize: system.config.pageSize,
  721. pageList: system.config.pageList,
  722. idField: "id",
  723. fit: true,
  724. striped: true,
  725. sortName: system.userConfig.torrentList.sortName,
  726. sortOrder: system.userConfig.torrentList.sortOrder,
  727. drophead: true,
  728. columns: [fields],
  729. onCheck: function (rowIndex, rowData) {
  730. system.checkTorrentRow(rowIndex, rowData);
  731. },
  732. onUncheck: function (rowIndex, rowData) {
  733. system.checkTorrentRow(rowIndex, rowData);
  734. },
  735. onCheckAll: function (rows) {
  736. system.checkTorrentRow("all", false);
  737. },
  738. onUncheckAll: function (rows) {
  739. system.checkTorrentRow("all", true);
  740. },
  741. onSelect: function (rowIndex, rowData) {
  742. if (selectedIndex != -1) {
  743. system.control.torrentlist.datagrid("unselectRow", selectedIndex);
  744. }
  745. system.getTorrentInfos(rowData.id);
  746. selectedIndex = rowIndex;
  747. },
  748. onUnselect: function (rowIndex, rowData) {
  749. system.currentTorrentId = 0;
  750. selectedIndex = -1;
  751. },
  752. // Before loading data
  753. onBeforeLoad: function (param) {
  754. system.currentTorrentId = 0;
  755. },
  756. // Header sorting
  757. onSortColumn: function (field, order) {
  758. var field_func = field;
  759. var datas = system.control.torrentlist.datagrid("getData").originalRows.sort(arrayObjectSort(field_func, order));
  760. system.control.torrentlist.datagrid("loadData", datas);
  761. system.resetTorrentListFieldsUserConfig(system.control.torrentlist.datagrid("options").columns[0]);
  762. system.userConfig.torrentList.sortName = field;
  763. system.userConfig.torrentList.sortOrder = order;
  764. system.saveUserConfig();
  765. },
  766. onRowContextMenu: function (e, rowIndex, rowData) {
  767. //console.log("onRowContextMenu");
  768. if (system.config.simpleCheckMode) {
  769. system.control.torrentlist.datagrid("uncheckAll");
  770. }
  771. // 当没有种子被选中时,选中当前行
  772. if (system.checkedRows.length==0) {
  773. system.control.torrentlist.datagrid("checkRow", rowIndex);
  774. }
  775. e.preventDefault();
  776. system.showContextMenu("torrent-list", e);
  777. },
  778. onHeadDrop: function (sourceField, targetField) {
  779. //console.log("onHeadDrop");
  780. system.resetTorrentListFieldsUserConfig(system.control.torrentlist.datagrid("options").columns[0]);
  781. system.saveUserConfig();
  782. },
  783. onResizeColumn: function (field, width) {
  784. system.resetTorrentListFieldsUserConfig(system.control.torrentlist.datagrid("options").columns[0]);
  785. system.saveUserConfig();
  786. },
  787. onHeaderContextMenu: function (e, field) {
  788. //console.log("onHeaderContextMenu");
  789. e.preventDefault();
  790. if (!headContextMenu) {
  791. createHeadContextMenu();
  792. }
  793. headContextMenu.menu('show', {
  794. left: e.pageX,
  795. top: e.pageY
  796. });
  797. }
  798. });
  799. }, "json");
  800. // 刷新当前页数据
  801. this.control.torrentlist.refresh = function() {
  802. system.control.torrentlist.datagrid("getPager").find(".pagination-load").click();
  803. };
  804. // Create a header right-click menu
  805. function createHeadContextMenu() {
  806. if (headContextMenu) {
  807. $(headContextMenu).remove();
  808. }
  809. headContextMenu = $('<div/>').appendTo('body');
  810. headContextMenu.menu({
  811. onClick: function (item) {
  812. if (item.iconCls == 'icon-ok') {
  813. system.control.torrentlist.datagrid('hideColumn', item.name);
  814. headContextMenu.menu('setIcon', {
  815. target: item.target,
  816. iconCls: 'icon-empty'
  817. });
  818. } else {
  819. system.control.torrentlist.datagrid('showColumn', item.name);
  820. headContextMenu.menu('setIcon', {
  821. target: item.target,
  822. iconCls: 'icon-ok'
  823. });
  824. }
  825. system.resetTorrentListFieldsUserConfig(system.control.torrentlist.datagrid("options").columns[0]);
  826. system.saveUserConfig();
  827. }
  828. });
  829. var fields = system.control.torrentlist.datagrid('getColumnFields');
  830. for (var i = 0; i < fields.length; i++) {
  831. var field = fields[i];
  832. var col = system.control.torrentlist.datagrid('getColumnOption', field);
  833. if (col.allowCustom != false && col.allowCustom != "false") {
  834. headContextMenu.menu('appendItem', {
  835. text: col.title,
  836. name: field,
  837. iconCls: (col.hidden ? "icon-empty" : "icon-ok")
  838. });
  839. }
  840. }
  841. }
  842. /*
  843. this.panel.list.bind('contextmenu',function(e){
  844. e.preventDefault();
  845. system.showContextMenu("torrent-list",e);
  846. });
  847. */
  848. },
  849. resetTorrentListFieldsUserConfig: function (columns) {
  850. var fields = {};
  851. $.each(this.userConfig.torrentList.fields, function (index, item) {
  852. fields[item.field] = item;
  853. });
  854. this.userConfig.torrentList.fields = [];
  855. $.each(columns, function (index, item) {
  856. var field = $.extend({}, fields[item.field]);
  857. field.width = item.width;
  858. field.hidden = item.hidden;
  859. system.userConfig.torrentList.fields.push(field);
  860. });
  861. },
  862. // Show context menu
  863. showContextMenu: function (type, e) {
  864. var parent = this.contextMenus[type];
  865. if (!parent) {
  866. parent = $("<div/>").attr("class", "easyui-menu").css({
  867. "min-width": "180px"
  868. }).appendTo(this.panel.main);
  869. this.contextMenus[type] = parent;
  870. parent.menu();
  871. } else {
  872. parent.empty();
  873. }
  874. var menus = null;
  875. switch (type) {
  876. case "torrent-list":
  877. menus = new Array("start", "pause", "-",
  878. "rename", "remove", "recheck", "-",
  879. "morepeers", "changeDownloadDir", "copyPath", "-",
  880. "menu-queue-move-top", "menu-queue-move-up", "menu-queue-move-down", "menu-queue-move-bottom",
  881. "magnetLink"
  882. );
  883. // 是否显示标签菜单
  884. if (this.config.nav.labels) {
  885. menus.push("-");
  886. menus.push("setLabels");
  887. }
  888. var toolbar = this.panel.toolbar;
  889. for (var item in menus) {
  890. var key = menus[item];
  891. if (key == "-") {
  892. $("<div class='menu-sep'></div>").appendTo(parent);
  893. } else {
  894. var menu = toolbar.find("#toolbar_" + key);
  895. if (menu.length > 0) {
  896. parent.menu("appendItem", {
  897. text: menu.attr("title"),
  898. id: key,
  899. iconCls: menu.linkbutton("options").iconCls,
  900. disabled: menu.linkbutton("options").disabled,
  901. onclick: function () {
  902. system.panel.toolbar.find("#toolbar_" + $(this).attr("id")).click();
  903. }
  904. });
  905. } else {
  906. menu = $("#" + key);
  907. if (menu.length > 0) {
  908. parent.menu("appendItem", {
  909. text: menu.attr("title"),
  910. id: key,
  911. iconCls: menu.attr("id").replace("menu-queue-move", "iconfont tr-icon"),
  912. disabled: toolbar.find("#toolbar_queue").linkbutton("options").disabled,
  913. onclick: function () {
  914. $("#" + $(this).attr("id")).click();
  915. }
  916. });
  917. } else {
  918. menu = this.getContentMenuWithKey(key, parent);
  919. if (menu) {
  920. parent.menu("appendItem", menu);
  921. }
  922. }
  923. }
  924. menu = null;
  925. }
  926. }
  927. // 设置剪切板组件,因为直接调用 click 不能执行相关操作
  928. var btn = $('#copyPath', parent);
  929. btn.attr({
  930. "data-clipboard-action": "copy",
  931. "data-clipboard-target": "#clipboard-source"
  932. });
  933. var clipboard = new ClipboardJS(btn.get(0));
  934. break;
  935. }
  936. parent.menu("show", {
  937. left: e.pageX,
  938. top: e.pageY,
  939. hideOnUnhover: false
  940. });
  941. parent = null;
  942. menus = null;
  943. },
  944. /**
  945. * 根据指定的key获取右键菜单
  946. * @param key
  947. * @param parent 父节点
  948. * @return 菜单对象
  949. */
  950. getContentMenuWithKey: function(key, parent) {
  951. switch (key) {
  952. case "setLabels":
  953. return {
  954. id: "setLabels",
  955. text: system.lang.menus.setLabels,
  956. iconCls: "iconfont tr-icon-labels",
  957. disabled: this.checkedRows.length==0,
  958. onclick: function() {
  959. var rows = system.checkedRows;
  960. var values = new Array();
  961. for (var i in rows) {
  962. values.push(rows[i].hashString);
  963. }
  964. if (values.length == 0) return;
  965. system.openDialogFromTemplate({
  966. id: "dialog-torrent-setLabels",
  967. options: {
  968. title: system.lang.dialog["torrent-setLabels"].title,
  969. width: 520,
  970. height: 200
  971. },
  972. datas: {
  973. "hashs": values
  974. }
  975. });
  976. }
  977. };
  978. case "magnetLink":
  979. return{
  980. id: "magnetLink",
  981. text: system.lang.menus.copyMagnetLink,
  982. iconCls: "iconfont tr-icon-labels",
  983. disabled: this.checkedRows.length==0,
  984. onclick: function() {
  985. system.getTorrentMagnetLink(function(data){
  986. system.copyToClipboard(data);
  987. parent.css("display","block"); // 防止第一次复制碰链失败
  988. });
  989. }
  990. }
  991. }
  992. },
  993. /**
  994. * 格式化指定种子的标签
  995. * @param ids 标签id列表, 数组
  996. * @param hashString 种子的hash值
  997. * @return 返回一组标签内容
  998. */
  999. formetTorrentLabels: function(ids, hashString) {
  1000. var box = $("<div style='position: relative;'/>");
  1001. if (ids) {
  1002. if (typeof(ids)=="string") {
  1003. ids = ids.split(",");
  1004. }
  1005. for (var i = 0; i < ids.length; i++) {
  1006. var index = ids[i];
  1007. var item = this.config.labels[index];
  1008. if (item) {
  1009. $("<span class='user-label'/>").html(item.name).css({
  1010. "background-color": item.color,
  1011. "color": (getGrayLevel(item.color) > 0.5 ? "#000" : "#fff")
  1012. }).appendTo(box);
  1013. }
  1014. }
  1015. }
  1016. var button = $("<button onclick='javascript:system.setTorrentLabels(this,\""+hashString+"\");' data-options=\"iconCls:'iconfont tr-icon-labels',plain:true\" class=\"easyui-linkbutton user-label-set\"/>").appendTo(box);
  1017. button.linkbutton();
  1018. button.find("span").first().attr({
  1019. "title": system.lang.dialog["torrent-setLabels"].title
  1020. });
  1021. return box.get(0).outerHTML;
  1022. },
  1023. /**
  1024. * 快速设置当前种子标签
  1025. */
  1026. setTorrentLabels: function(button, hashString) {
  1027. system.openDialogFromTemplate({
  1028. id: "dialog-torrent-setLabels",
  1029. options: {
  1030. title: system.lang.dialog["torrent-setLabels"].title,
  1031. width: 520,
  1032. height: 200
  1033. },
  1034. datas: {
  1035. "hashs": [hashString]
  1036. },
  1037. type: 1,
  1038. source: $(button)
  1039. });
  1040. },
  1041. /**
  1042. * 选中或反选种子时,改变菜单的可操作状态
  1043. * @param rowIndex 当前行索引,当全选/反选时为 'all'
  1044. * @param rowData 当前行数据,当全选/反选时为 true 或 false,全选为false, 全反选为 true
  1045. * @return void
  1046. */
  1047. checkTorrentRow: function (rowIndex, rowData) {
  1048. // 获取当前已选中的行
  1049. this.checkedRows = this.control.torrentlist.datagrid("getChecked");
  1050. this.showCheckedInStatus();
  1051. // 是否全选或反选
  1052. if (rowIndex == "all") {
  1053. if (this.control.torrentlist.datagrid("getRows").length==0) {
  1054. return;
  1055. }
  1056. $("#toolbar_start, #toolbar_pause, #toolbar_remove, #toolbar_recheck, #toolbar_changeDownloadDir,#toolbar_changeSpeedLimit,#toolbar_morepeers,#toolbar_copyPath", this.panel.toolbar).linkbutton({
  1057. disabled: rowData
  1058. });
  1059. $("#toolbar_rename, #toolbar_morepeers", this.panel.toolbar).linkbutton({
  1060. disabled: true
  1061. });
  1062. this.panel.toolbar.find("#toolbar_queue").menubutton("disable");
  1063. return;
  1064. }
  1065. // 如果没有被选中的数据时
  1066. if (this.checkedRows.length == 0) {
  1067. // 禁用所有菜单
  1068. $("#toolbar_start, #toolbar_pause, #toolbar_rename, #toolbar_remove, #toolbar_recheck, #toolbar_changeDownloadDir,#toolbar_changeSpeedLimit,#toolbar_morepeers,#toolbar_copyPath", this.panel.toolbar).linkbutton({
  1069. disabled: true
  1070. });
  1071. this.panel.toolbar.find("#toolbar_queue").menubutton("disable");
  1072. return;
  1073. // 当仅有一条数据被选中时
  1074. } else if (this.checkedRows.length == 1) {
  1075. // 设置 删除、改名、变更保存目录、移动队列功能可用
  1076. $("#toolbar_remove, #toolbar_rename, #toolbar_changeDownloadDir,#toolbar_changeSpeedLimit,#toolbar_copyPath", this.panel.toolbar).linkbutton({
  1077. disabled: false
  1078. });
  1079. this.panel.toolbar.find("#toolbar_queue").menubutton("enable");
  1080. var torrent = transmission.torrents.all[rowData.id];
  1081. // 确认当前种子状态
  1082. switch (torrent.status) {
  1083. // 已停止
  1084. case transmission._status.stopped:
  1085. this.panel.toolbar.find("#toolbar_start, #toolbar_recheck").linkbutton({
  1086. disabled: false
  1087. });
  1088. this.panel.toolbar.find("#toolbar_pause, #toolbar_morepeers").linkbutton({
  1089. disabled: true
  1090. });
  1091. break;
  1092. // 校验
  1093. case transmission._status.check:
  1094. case transmission._status.checkwait:
  1095. this.panel.toolbar.find("#toolbar_start, #toolbar_pause, #toolbar_recheck, #toolbar_morepeers").linkbutton({
  1096. disabled: true
  1097. });
  1098. break;
  1099. // 其他
  1100. default:
  1101. this.panel.toolbar.find("#toolbar_start, #toolbar_recheck").linkbutton({
  1102. disabled: true
  1103. });
  1104. this.panel.toolbar.find("#toolbar_pause, #toolbar_morepeers").linkbutton({
  1105. disabled: false
  1106. });
  1107. break;
  1108. }
  1109. // 多条数据被选中时
  1110. } else {
  1111. $("#toolbar_start, #toolbar_pause, #toolbar_remove, #toolbar_recheck, #toolbar_changeDownloadDir,#toolbar_changeSpeedLimit,#toolbar_copyPath", this.panel.toolbar).linkbutton({
  1112. disabled: false
  1113. });
  1114. $("#toolbar_rename, #toolbar_morepeers", this.panel.toolbar).linkbutton({
  1115. disabled: true
  1116. });
  1117. this.panel.toolbar.find("#toolbar_queue").menubutton("disable");
  1118. }
  1119. },
  1120. /**
  1121. * 显示已选中的内容
  1122. */
  1123. showCheckedInStatus: function() {
  1124. if (this.checkedRows.length>0) {
  1125. this.panel.status_text.empty();
  1126. this.showStatus(undefined, 0);
  1127. var items = [];
  1128. var text = this.lang.system.status.checked.replace("%n", this.checkedRows.length);
  1129. var paths = [];
  1130. $("<div style='padding: 5px;'/>").html(text).appendTo(this.panel.status_text);
  1131. for (var index = 0; index < this.checkedRows.length; index++) {
  1132. var item = this.checkedRows[index];
  1133. items.push({value: index, text: (index+1)+". "+item.name});
  1134. if ($.inArray(item.downloadDir, paths)===-1) {
  1135. paths.push(item.downloadDir);
  1136. }
  1137. }
  1138. $("<div/>").appendTo(this.panel.status_text).datalist({
  1139. data: items
  1140. });
  1141. $(".datalist>.panel-body", this.panel.status_text).css({
  1142. border: 0
  1143. });
  1144. $("#button-cancel-checked").show();
  1145. $("#clipboard-source").val(paths.join("\n"));
  1146. } else {
  1147. // this.showStatus("无", 100);
  1148. $("#button-cancel-checked").hide();
  1149. this.panel.status_text.empty();
  1150. $("#clipboard-source").val("");
  1151. }
  1152. },
  1153. // by https://stackoverflow.com/questions/22581345/click-button-copy-to-clipboard-using-jquery?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
  1154. copyToClipboard: function (text) {
  1155. // Create a "hidden" input
  1156. var id = "copy_to_clipboard_textarea";
  1157. var aux = document.getElementById(id);
  1158. if(!aux) aux = document.createElement("textarea"); // <input/> 不接受换行
  1159. aux.id = id;
  1160. aux.style.display = "block";
  1161. // Assign it the value of the specified element
  1162. aux.value = text; // <textarea/> 不能使用 setAttribute
  1163. // Append it to the body
  1164. document.body.appendChild(aux);
  1165. // Highlight its content
  1166. aux.select();
  1167. // Copy the highlighted text
  1168. document.execCommand("copy");
  1169. // Remove it from the body
  1170. aux.style.display = "none";
  1171. },
  1172. // Initialize the System Toolbar
  1173. initToolbar: function () {
  1174. // refresh time
  1175. this.panel.toolbar.find("#toolbar_label_reload_time").html(this.lang.toolbar["reload-time"]);
  1176. this.panel.toolbar.find("#toolbar_label_reload_time_unit").html(this.lang.toolbar["reload-time-unit"]);
  1177. this.panel.toolbar.find("#toolbar_reload_time").numberspinner({
  1178. value: this.config.reloadStep / 1000,
  1179. min: 3,
  1180. disabled: !this.config.autoReload,
  1181. onChange: function () {
  1182. var value = this.value;
  1183. if ($.isNumeric(value)) {
  1184. system.config.reloadStep = value * 1000;
  1185. system.saveConfig();
  1186. }
  1187. }
  1188. });
  1189. // Enable / disable auto-refresh
  1190. this.panel.toolbar.find("#toolbar_autoreload")
  1191. .linkbutton({
  1192. text: (this.config.autoReload ? this.lang.toolbar["autoreload-enabled"] : this.lang.toolbar["autoreload-disabled"]),
  1193. iconCls: (this.config.autoReload ? "icon-enabled" : "icon-disabled")
  1194. })
  1195. .attr("title", (this.config.autoReload ? this.lang.toolbar.tip["autoreload-disabled"] : this.lang.toolbar.tip["autoreload-enabled"]))
  1196. .click(function () {
  1197. if (system.config.autoReload) {
  1198. system.config.autoReload = false;
  1199. clearTimeout(system.autoReloadTimer);
  1200. system.panel.toolbar.find("#toolbar_reload_time").numberspinner("disable");
  1201. } else {
  1202. system.config.autoReload = true;
  1203. system.reloadData();
  1204. system.panel.toolbar.find("#toolbar_reload_time").numberspinner("enable");
  1205. }
  1206. system.saveConfig();
  1207. $(this).linkbutton({
  1208. text: (system.config.autoReload ? system.lang.toolbar["autoreload-enabled"] : system.lang.toolbar["autoreload-disabled"]),
  1209. iconCls: (system.config.autoReload ? "icon-enabled" : "icon-disabled")
  1210. })
  1211. .attr("title", (system.config.autoReload ? system.lang.toolbar.tip["autoreload-disabled"] : system.lang.toolbar.tip["autoreload-enabled"]));
  1212. });
  1213. // Add torrents
  1214. this.panel.toolbar.find("#toolbar_add_torrents")
  1215. .linkbutton({
  1216. text: this.lang.toolbar["add-torrent"],
  1217. disabled: false
  1218. })
  1219. .attr("title", this.lang.toolbar.tip["add-torrent"])
  1220. .click(function () {
  1221. system.openDialogFromTemplate({
  1222. id: "dialog-torrent-add",
  1223. options: {
  1224. title: system.lang.toolbar["add-torrent"],
  1225. width: 620,
  1226. height: system.config.nav.labels ? 600 : 400,
  1227. resizable: true
  1228. }
  1229. });
  1230. });
  1231. // Start all
  1232. this.panel.toolbar.find("#toolbar_start_all")
  1233. //.linkbutton({text:this.lang.toolbar["start-all"],disabled:false})
  1234. .linkbutton({
  1235. disabled: false
  1236. })
  1237. .attr("title", this.lang.toolbar.tip["start-all"])
  1238. .click(function () {
  1239. var button = $(this);
  1240. var icon = button.linkbutton("options").iconCls;
  1241. button.linkbutton({
  1242. disabled: true,
  1243. iconCls: "icon-loading"
  1244. });
  1245. transmission.exec({
  1246. method: "torrent-start"
  1247. }, function (data) {
  1248. button.linkbutton({
  1249. iconCls: icon,
  1250. disabled: false
  1251. });
  1252. button = null;
  1253. });
  1254. });
  1255. // Pause all
  1256. this.panel.toolbar.find("#toolbar_pause_all")
  1257. //.linkbutton({text:this.lang.toolbar["pause-all"],disabled:false})
  1258. .linkbutton({
  1259. disabled: false
  1260. })
  1261. .attr("title", this.lang.toolbar.tip["pause-all"])
  1262. .click(function () {
  1263. var button = $(this);
  1264. var icon = button.linkbutton("options").iconCls;
  1265. button.linkbutton({
  1266. disabled: true,
  1267. iconCls: "icon-loading"
  1268. });
  1269. transmission.exec({
  1270. method: "torrent-stop"
  1271. }, function (data) {
  1272. button.linkbutton({
  1273. iconCls: icon,
  1274. disabled: false
  1275. });
  1276. button = null;
  1277. });
  1278. });
  1279. // Start Selected
  1280. this.panel.toolbar.find("#toolbar_start")
  1281. .linkbutton({
  1282. disabled: true
  1283. })
  1284. .attr("title", this.lang.toolbar.tip["start"])
  1285. .click(function () {
  1286. system.changeSelectedTorrentStatus("start", $(this));
  1287. });
  1288. // Pause Selected
  1289. this.panel.toolbar.find("#toolbar_pause")
  1290. .linkbutton({
  1291. disabled: true
  1292. })
  1293. .attr("title", this.lang.toolbar.tip["pause"])
  1294. .click(function () {
  1295. system.changeSelectedTorrentStatus("stop", $(this));
  1296. });
  1297. // Recalculate selected
  1298. this.panel.toolbar.find("#toolbar_recheck")
  1299. .linkbutton({
  1300. disabled: true
  1301. })
  1302. .attr("title", this.lang.toolbar.tip["recheck"])
  1303. .click(function () {
  1304. var rows = system.control.torrentlist.datagrid("getChecked");
  1305. if (rows.length > 0) {
  1306. if (rows.length == 1) {
  1307. var torrent = transmission.torrents.all[rows[0].id];
  1308. if (torrent.percentDone > 0) {
  1309. if (confirm(system.lang.toolbar.tip["recheck-confirm"])) {
  1310. system.changeSelectedTorrentStatus("verify", $(this));
  1311. }
  1312. } else {
  1313. system.changeSelectedTorrentStatus("verify", $(this));
  1314. }
  1315. } else if (confirm(system.lang.toolbar.tip["recheck-confirm"])) {
  1316. system.changeSelectedTorrentStatus("verify", $(this));
  1317. }
  1318. }
  1319. });
  1320. // Get more peers
  1321. this.panel.toolbar.find("#toolbar_morepeers")
  1322. .linkbutton({
  1323. disabled: true
  1324. })
  1325. .click(function () {
  1326. system.changeSelectedTorrentStatus("reannounce", $(this));
  1327. });
  1328. // Deletes the selected
  1329. this.panel.toolbar.find("#toolbar_remove")
  1330. .linkbutton({
  1331. disabled: true
  1332. })
  1333. .attr("title", this.lang.toolbar.tip["remove"])
  1334. .click(function () {
  1335. var rows = system.control.torrentlist.datagrid("getChecked");
  1336. var ids = new Array();
  1337. for (var i in rows) {
  1338. ids.push(rows[i].id);
  1339. }
  1340. if (ids.length == 0) return;
  1341. system.openDialogFromTemplate({
  1342. id: "dialog-torrent-remove-confirm",
  1343. options: {
  1344. title: system.lang.dialog["torrent-remove"].title,
  1345. width: 350,
  1346. height: 150
  1347. },
  1348. datas: {
  1349. "ids": ids
  1350. }
  1351. });
  1352. });
  1353. // Renames the selected
  1354. this.panel.toolbar.find("#toolbar_rename")
  1355. .linkbutton({
  1356. disabled: true
  1357. })
  1358. .click(function () {
  1359. var rows = system.control.torrentlist.datagrid("getChecked");
  1360. if (rows.length == 0) return;
  1361. system.openDialogFromTemplate({
  1362. id: "dialog-torrent-rename",
  1363. options: {
  1364. title: system.lang.dialog["torrent-rename"].title,
  1365. width: 520,
  1366. height: 200,
  1367. resizable: true
  1368. },
  1369. datas: {
  1370. id: rows[0].id
  1371. }
  1372. });
  1373. });
  1374. // Modify the selected torrent data save directory
  1375. this.panel.toolbar.find("#toolbar_changeDownloadDir")
  1376. .linkbutton({
  1377. disabled: true
  1378. })
  1379. .attr("title", this.lang.toolbar.tip["change-download-dir"])
  1380. .click(function () {
  1381. var rows = system.control.torrentlist.datagrid("getChecked");
  1382. var ids = new Array();
  1383. for (var i in rows) {
  1384. ids.push(rows[i].id);
  1385. }
  1386. if (ids.length == 0) return;
  1387. system.openDialogFromTemplate({
  1388. id: "dialog-torrent-changeDownloadDir",
  1389. options: {
  1390. title: system.lang.dialog["torrent-changeDownloadDir"].title,
  1391. width: 520,
  1392. height: 200
  1393. },
  1394. datas: {
  1395. "ids": ids
  1396. }
  1397. });
  1398. });
  1399. this.panel.toolbar
  1400. .find("#toolbar_changeSpeedLimit")
  1401. .linkbutton({
  1402. disabled: true,
  1403. })
  1404. .attr("title", this.lang.toolbar.tip["change-speedlimit"])
  1405. .click(function () {
  1406. var rows = system.control.torrentlist.datagrid("getChecked");
  1407. var ids = new Array();
  1408. for (var i in rows) {
  1409. ids.push(rows[i].id);
  1410. }
  1411. if (ids.length == 0) return;
  1412. system.openDialogFromTemplate({
  1413. id: "dialog-torrent-changeSpeedLimit",
  1414. options: {
  1415. title: system.lang.dialog["torrent-changeSpeedLimit"].title,
  1416. width: 600,
  1417. height: 200,
  1418. resizable: true,
  1419. },
  1420. datas: {
  1421. ids: ids,
  1422. },
  1423. type: 0,
  1424. });
  1425. });
  1426. // Speed limit
  1427. this.panel.toolbar.find("#toolbar_alt_speed")
  1428. .linkbutton()
  1429. .attr("title", this.lang.toolbar.tip["alt-speed"])
  1430. .click(function () {
  1431. var button = $(this);
  1432. var options = button.linkbutton("options");
  1433. var enabled = false;
  1434. if (options.iconCls == "iconfont tr-icon-rocket") {
  1435. enabled = true;
  1436. }
  1437. transmission.exec({
  1438. method: "session-set",
  1439. arguments: {
  1440. "alt-speed-enabled": enabled
  1441. }
  1442. }, function (data) {
  1443. if (data.result == "success") {
  1444. system.serverConfig["alt-speed-enabled"] = enabled;
  1445. button.linkbutton({
  1446. iconCls: "iconfont tr-icon-" + (enabled?"woniu":"rocket")//"icon-alt-speed-" + enabled.toString()
  1447. });
  1448. if (enabled) {
  1449. $("#status_alt_speed").show();
  1450. } else {
  1451. $("#status_alt_speed").hide();
  1452. }
  1453. }
  1454. });
  1455. button.linkbutton({
  1456. iconCls: "icon-loading"
  1457. });
  1458. });
  1459. // configuration
  1460. this.panel.toolbar.find("#toolbar_config")
  1461. .linkbutton()
  1462. .attr("title", this.lang.toolbar.tip["system-config"])
  1463. .click(function () {
  1464. system.openDialogFromTemplate({
  1465. id: "dialog-system-config",
  1466. options: {
  1467. title: system.lang.toolbar["system-config"],
  1468. width: 680,
  1469. height: 500,
  1470. resizable: true
  1471. }
  1472. });
  1473. });
  1474. // reload
  1475. this.panel.toolbar.find("#toolbar_reload")
  1476. .linkbutton()
  1477. .attr("title", this.lang.toolbar.tip["system-reload"])
  1478. .click(function () {
  1479. system.reloadData();
  1480. });
  1481. // search
  1482. this.panel.toolbar.find("#toolbar_search").searchbox({
  1483. searcher: function (value) {
  1484. system.searchTorrents(value);
  1485. },
  1486. prompt: this.lang.toolbar["search-prompt"]
  1487. });
  1488. this.panel.toolbar.find("#toolbar_copyPath")
  1489. .linkbutton()
  1490. .attr("title", this.lang.toolbar.tip["copy-path-to-clipboard"]);
  1491. },
  1492. // Initialize the status bar
  1493. initStatusBar: function () {
  1494. this.panel.statusbar.find("#status_title_downloadspeed").html(this.lang.statusbar.downloadspeed);
  1495. this.panel.statusbar.find("#status_title_uploadspeed").html(this.lang.statusbar.uploadspeed);
  1496. },
  1497. // connect to the server
  1498. connect: function () {
  1499. this.showStatus(this.lang.system.status.connect, 0);
  1500. // When the total torrent number is changed, the torrent information is retrieved
  1501. transmission.on.torrentCountChange = function () {
  1502. system.reloadTorrentBaseInfos();
  1503. };
  1504. // When submitting an error
  1505. transmission.on.postError = function () {
  1506. //system.reloadTorrentBaseInfos();
  1507. };
  1508. // Initialize the connection
  1509. transmission.init({
  1510. islocal: true
  1511. }, function () {
  1512. system.reloadSession(true);
  1513. system.getServerStatus();
  1514. });
  1515. },
  1516. // Reload the server information
  1517. reloadSession: function (isinit) {
  1518. transmission.getSession(function (result) {
  1519. system.serverConfig = result;
  1520. // Version Information
  1521. $("#status_version").html("Transmission " + system.lang.statusbar.version + result["version"] + ", RPC: " + result["rpc-version"] +
  1522. ", WEB Control: " + system.version + "(" + system.codeupdate + ")");
  1523. if (result["alt-speed-enabled"] == true) {
  1524. system.panel.toolbar.find("#toolbar_alt_speed").linkbutton({
  1525. iconCls: "iconfont tr-icon-woniu"
  1526. });
  1527. $("#status_alt_speed").show();
  1528. } else {
  1529. system.panel.toolbar.find("#toolbar_alt_speed").linkbutton({
  1530. iconCls: "iconfont tr-icon-rocket"
  1531. });
  1532. $("#status_alt_speed").hide();
  1533. }
  1534. system.downloadDir = result["download-dir"];
  1535. // Always push default download dir to the Dirs array
  1536. if (transmission.downloadDirs.length == 0) {
  1537. transmission.downloadDirs.push(system.downloadDir);
  1538. }
  1539. // Rpc-version version 15, no longer provide download-dir-free-space parameters, to be obtained from the new method
  1540. if (parseInt(system.serverConfig["rpc-version"]) >= 15) {
  1541. transmission.getFreeSpace(system.downloadDir, function (datas) {
  1542. system.serverConfig["download-dir-free-space"] = datas.arguments["size-bytes"];
  1543. system.showFreeSpace(datas.arguments["size-bytes"]);
  1544. });
  1545. } else {
  1546. system.showFreeSpace(system.serverConfig["download-dir-free-space"]);
  1547. }
  1548. if (isinit) {
  1549. system.showStatus(system.lang.system.status.connected);
  1550. }
  1551. });
  1552. },
  1553. showFreeSpace: function (size) {
  1554. var tmp = size;
  1555. if (tmp == -1) {
  1556. tmp = system.lang["public"]["text-unknown"];
  1557. } else {
  1558. tmp = formatSize(tmp);
  1559. }
  1560. $("#status_freespace").text(system.lang.dialog["system-config"]["download-dir-free-space"] + " " + tmp);
  1561. },
  1562. // Retrieve the torrent information again
  1563. reloadTorrentBaseInfos: function (ids, moreFields) {
  1564. if (this.reloading) return;
  1565. clearTimeout(this.autoReloadTimer);
  1566. this.reloading = true;
  1567. var oldInfos = {
  1568. trackers: transmission.trackers,
  1569. folders: transmission.torrents.folders
  1570. }
  1571. // Gets all the torrent id information
  1572. transmission.torrents.getallids(function (resultTorrents) {
  1573. var ignore = new Array();
  1574. for (var index in resultTorrents) {
  1575. var item = resultTorrents[index];
  1576. ignore.push(item.id);
  1577. }
  1578. // Error numbered list
  1579. var errorIds = transmission.torrents.getErrorIds(ignore, true);
  1580. if (errorIds.length > 0) {
  1581. transmission.torrents.getallids(function () {
  1582. system.resetTorrentInfos(oldInfos);
  1583. }, errorIds);
  1584. } else {
  1585. system.resetTorrentInfos(oldInfos);
  1586. }
  1587. }, ids, moreFields);
  1588. },
  1589. // refresh the tree
  1590. resetTorrentInfos: function (oldInfos) {
  1591. this.resetNavTorrentStatus();
  1592. this.resetNavServers(oldInfos);
  1593. this.resetNavStatistics();
  1594. this.resetNavFolders(oldInfos);
  1595. this.resetNavLabels();
  1596. // FF browser displays the total size, will be moved down a row, so a separate treatment
  1597. // 新版本已无此问题
  1598. if ($.ua.browser.name == "Firefox" && $.ua.browser.major < 60) {
  1599. system.panel.left.find("span.nav-total-size").css({
  1600. "margin-top": "-19px"
  1601. });
  1602. }
  1603. },
  1604. /**
  1605. * 重置导航栏种子状态信息
  1606. */
  1607. resetNavTorrentStatus: function() {
  1608. var currentTorrentId = this.currentTorrentId;
  1609. // Paused
  1610. if (transmission.torrents.status[transmission._status.stopped]) {
  1611. system.updateTreeNodeText("paused", system.lang.tree.paused + this.showNodeMoreInfos(transmission.torrents.status[transmission._status.stopped].length));
  1612. } else {
  1613. system.updateTreeNodeText("paused", system.lang.tree.paused);
  1614. }
  1615. // Seeding
  1616. if (transmission.torrents.status[transmission._status.seed]) {
  1617. system.updateTreeNodeText("sending", system.lang.tree.sending + this.showNodeMoreInfos(transmission.torrents.status[transmission._status.seed].length));
  1618. } else {
  1619. system.updateTreeNodeText("sending", system.lang.tree.sending);
  1620. }
  1621. // Waiting for seed
  1622. if (transmission.torrents.status[transmission._status.seedwait]) {
  1623. var node = system.panel.left.tree("find", "sending");
  1624. var childs = system.panel.left.tree("getChildren", node.target);
  1625. var text = system.lang.tree.wait + this.showNodeMoreInfos(transmission.torrents.status[transmission._status.seedwait].length);
  1626. if (childs.length > 0) {
  1627. system.updateTreeNodeText(childs[0].id, text);
  1628. } else {
  1629. system.appendTreeNode(node, [{
  1630. id: "seedwait",
  1631. text: text,
  1632. iconCls: "iconfont tr-icon-wait"
  1633. }]);
  1634. }
  1635. } else {
  1636. system.removeTreeNode("seedwait");
  1637. }
  1638. // check
  1639. if (transmission.torrents.status[transmission._status.check]) {
  1640. system.updateTreeNodeText("check", system.lang.tree.check + this.showNodeMoreInfos(transmission.torrents.status[transmission._status.check].length));
  1641. } else {
  1642. system.updateTreeNodeText("check", system.lang.tree.check);
  1643. }
  1644. // Waiting for check
  1645. if (transmission.torrents.status[transmission._status.checkwait]) {
  1646. var node = system.panel.left.tree("find", "check");
  1647. var childs = system.panel.left.tree("getChildren", node.target);
  1648. var text = system.lang.tree.wait + this.showNodeMoreInfos(transmission.torrents.status[transmission._status.checkwait].length);
  1649. if (childs.length > 0) {
  1650. system.updateTreeNodeText(childs[0].id, text);
  1651. } else {
  1652. system.appendTreeNode(node, [{
  1653. id: "checkwait",
  1654. text: text,
  1655. iconCls: "iconfont tr-icon-wait"
  1656. }]);
  1657. }
  1658. } else {
  1659. system.removeTreeNode("checkwait");
  1660. }
  1661. // downloading
  1662. if (transmission.torrents.status[transmission._status.download]) {
  1663. system.updateTreeNodeText("downloading", system.lang.tree.downloading + this.showNodeMoreInfos(transmission.torrents.status[transmission._status.download].length));
  1664. } else {
  1665. system.updateTreeNodeText("downloading", system.lang.tree.downloading);
  1666. }
  1667. // Waiting for download
  1668. if (transmission.torrents.status[transmission._status.downloadwait]) {
  1669. var node = system.panel.left.tree("find", "downloading");
  1670. var childs = system.panel.left.tree("getChildren", node.target);
  1671. var text = system.lang.tree.wait + this.showNodeMoreInfos(transmission.torrents.status[transmission._status.downloadwait].length);
  1672. if (childs.length > 0) {
  1673. system.updateTreeNodeText(childs[0].id, text);
  1674. } else {
  1675. system.appendTreeNode(node, [{
  1676. id: "downloadwait",
  1677. text: text,
  1678. iconCls: "iconfont tr-icon-wait"
  1679. }]);
  1680. }
  1681. } else {
  1682. system.removeTreeNode("downloadwait");
  1683. }
  1684. // Active
  1685. system.updateTreeNodeText("actively", system.lang.tree.actively + this.showNodeMoreInfos(transmission.torrents.actively.length));
  1686. // With error
  1687. system.updateTreeNodeText("error", system.lang.tree.error + this.showNodeMoreInfos(transmission.torrents.error.length));
  1688. // With warning
  1689. system.updateTreeNodeText("warning", system.lang.tree.warning + this.showNodeMoreInfos(transmission.torrents.warning.length));
  1690. var node = system.panel.left.tree("getSelected");
  1691. if (node != null) {
  1692. var p = system.control.torrentlist.datagrid("options").pageNumber;
  1693. system.loadTorrentToList({
  1694. node: node,
  1695. page: p
  1696. });
  1697. }
  1698. if (currentTorrentId != 0) {
  1699. system.control.torrentlist.datagrid("selectRecord", currentTorrentId);
  1700. }
  1701. system.reloading = false;
  1702. if (system.config.autoReload) {
  1703. system.autoReloadTimer = setTimeout(function () {
  1704. system.reloadData();
  1705. }, system.config.reloadStep);
  1706. }
  1707. // Total count
  1708. system.updateTreeNodeText("torrent-all", system.lang.tree.all + this.showNodeMoreInfos(transmission.torrents.count, transmission.torrents.totalSize));
  1709. },
  1710. /**
  1711. * 重置导航栏服务器信息
  1712. */
  1713. resetNavServers: function(oldInfos) {
  1714. // 获取服务器分布主节点
  1715. var serversNode = this.panel.left.tree("find", "servers");
  1716. if (!this.config.nav.servers) {
  1717. if (serversNode) {
  1718. this.panel.left.tree("remove", serversNode.target);
  1719. }
  1720. return;
  1721. }
  1722. if (serversNode) {
  1723. var serversNode_collapsed = serversNode.state;
  1724. this.removeTreeNode("servers-loading");
  1725. } else {
  1726. this.appendTreeNode(null, [{
  1727. id: "servers",
  1728. text: this.lang.tree.servers,
  1729. state: "closed",
  1730. iconCls: "iconfont tr-icon-servers"
  1731. }]);
  1732. serversNode = this.panel.left.tree("find", "servers");
  1733. }
  1734. var datas = new Array();
  1735. var BTServersNode = this.panel.left.tree("find", "btservers");
  1736. var BTServersNodeState = (BTServersNode?BTServersNode.state:"close");
  1737. // 先添加一个“BT”目录节点,用于增加BT服务器列表
  1738. if (!BTServersNode && system.config.showBTServers) {
  1739. this.appendTreeNode(serversNode, [{
  1740. id: "btservers",
  1741. text: "BT",
  1742. state: "open",
  1743. iconCls: "iconfont tr-icon-bt"
  1744. }]);
  1745. BTServersNode = this.panel.left.tree("find", "btservers");
  1746. }
  1747. // 加载服务器列表
  1748. for (var index in transmission.trackers) {
  1749. var tracker = transmission.trackers[index];
  1750. if (tracker.isBT) {
  1751. // 是否显示BT服务器
  1752. if (!system.config.showBTServers) {
  1753. continue;
  1754. }
  1755. }
  1756. var node = system.panel.left.tree("find", tracker.nodeid);
  1757. var text = tracker.name + this.showNodeMoreInfos(tracker.count, tracker.size);
  1758. if (node) {
  1759. system.updateTreeNodeText(tracker.nodeid, text, (tracker.connected ? "iconfont tr-icon-server" : "iconfont tr-icon-server-error"));
  1760. } else {
  1761. system.appendTreeNode((tracker.isBT? BTServersNode: serversNode), [{
  1762. id: tracker.nodeid,
  1763. text: text,
  1764. iconCls: (tracker.connected ? "iconfont tr-icon-server" : "iconfont tr-icon-server-error")
  1765. }]);
  1766. }
  1767. oldInfos.trackers[tracker.nodeid] = null;
  1768. }
  1769. // Collapse the node if it was before
  1770. if (serversNode_collapsed == "closed") {
  1771. this.panel.left.tree("collapse", serversNode.target);
  1772. }
  1773. if (system.config.showBTServers && BTServersNode && BTServersNodeState == "closed") {
  1774. this.panel.left.tree("collapse", BTServersNode.target);
  1775. }
  1776. // Delete the server that no longer exists
  1777. for (var index in oldInfos.trackers) {
  1778. var tracker = oldInfos.trackers[index];
  1779. if (tracker) {
  1780. system.removeTreeNode(tracker.nodeid);
  1781. }
  1782. }
  1783. },
  1784. /**
  1785. * 重置导航栏数据统计信息
  1786. */
  1787. resetNavStatistics: function() {
  1788. if (!this.config.nav.statistics) {
  1789. var node = this.panel.left.tree("find", "statistics");
  1790. if (node) {
  1791. this.panel.left.tree("remove", node.target);
  1792. }
  1793. return;
  1794. }
  1795. // Statistics
  1796. var items = ("uploadedBytes,downloadedBytes,filesAdded,sessionCount,secondsActive").split(",");
  1797. $.each(items, function (key, item) {
  1798. switch (item) {
  1799. case "uploadedBytes":
  1800. case "downloadedBytes":
  1801. system.updateTreeNodeText(item, system.lang.tree.statistics[item] + " " + formatSize(system.serverSessionStats["cumulative-stats"][item]));
  1802. system.updateTreeNodeText("current-" + item, system.lang.tree.statistics[item] + " " + formatSize(system.serverSessionStats["current-stats"][item]));
  1803. break;
  1804. case "secondsActive":
  1805. system.updateTreeNodeText(item, system.lang.tree.statistics[item] + " " + getTotalTime(system.serverSessionStats["cumulative-stats"][item] * 1000));
  1806. system.updateTreeNodeText("current-" + item, system.lang.tree.statistics[item] + " " + getTotalTime(system.serverSessionStats["current-stats"][item] * 1000));
  1807. break;
  1808. default:
  1809. system.updateTreeNodeText(item, system.lang.tree.statistics[item] + " " + system.serverSessionStats["cumulative-stats"][item]);
  1810. system.updateTreeNodeText("current-" + item, system.lang.tree.statistics[item] + " " + system.serverSessionStats["current-stats"][item]);
  1811. break;
  1812. }
  1813. });
  1814. },
  1815. /**
  1816. * 重置导航栏数据目录信息
  1817. */
  1818. resetNavFolders: function(oldInfos) {
  1819. if (!this.config.nav.folders) {
  1820. this.initUIStatus();
  1821. var node = this.panel.left.tree("find", "folders");
  1822. if (node) {
  1823. this.panel.left.tree("remove", node.target);
  1824. }
  1825. return;
  1826. }
  1827. for (var index in transmission.torrents.folders) {
  1828. var item = transmission.torrents.folders[index];
  1829. oldInfos.folders[item.nodeid] = null;
  1830. }
  1831. // Loads the directory listing
  1832. this.loadFolderList(oldInfos.folders);
  1833. },
  1834. /**
  1835. * 重置导航栏用户标签信息
  1836. */
  1837. resetNavLabels: function(clear) {
  1838. if (!this.config.nav.labels) {
  1839. var node = this.panel.left.tree("find", "labels");
  1840. if (node) {
  1841. this.panel.left.tree("remove", node.target);
  1842. }
  1843. return;
  1844. }
  1845. if (clear) {
  1846. var items = this.panel.left.tree("getChildren", this.panel.left.tree("find","labels").target);
  1847. for (var index = 0; index < items.length; index++) {
  1848. this.panel.left.tree("remove", items[index].target);
  1849. }
  1850. }
  1851. var prefix = "label-";
  1852. for (var index = 0; index < this.config.labels.length; index++) {
  1853. var item = this.config.labels[index];
  1854. var key = prefix + this.getValidTreeKey(item.name);
  1855. var node = this.panel.left.tree("find", key);
  1856. if (!node) {
  1857. this.appendTreeNode("labels", [{
  1858. id: key,
  1859. text: item.name,
  1860. labelIndex: index,
  1861. iconCls: "iconfont tr-icon-label"
  1862. }]);
  1863. node = this.panel.left.tree("find", key);
  1864. $(".tree-icon", node.target).css({
  1865. color: item.color
  1866. });
  1867. $(".tree-title", node.target).addClass("user-label").css({
  1868. "background-color": item.color,
  1869. "color": (getGrayLevel(item.color) > 0.5 ? "#000" : "#fff")
  1870. });
  1871. }
  1872. }
  1873. },
  1874. // Displays the current torrent count and size
  1875. showNodeMoreInfos: function (count, size) {
  1876. var result = "";
  1877. if (count > 0) {
  1878. result = " <span class='nav-torrents-number'>(" + count + ")</span>";
  1879. }
  1880. if (size > 0) {
  1881. result += "<span class='nav-total-size'>[" + formatSize(size) + "]</span>";
  1882. }
  1883. return result;
  1884. },
  1885. // Gets the current state of the server
  1886. getServerStatus: function () {
  1887. if (this.reloading) return;
  1888. clearTimeout(this.autoReloadTimer);
  1889. this.reloading = true;
  1890. transmission.getStatus(function (data) {
  1891. system.reloading = false;
  1892. //system.updateTreeNodeText("torrent-all",system.lang.tree.all+" ("+data["torrentCount"]+")");
  1893. //system.updateTreeNodeText("paused",system.lang.tree.paused+(data["pausedTorrentCount"]==0?"":" ("+data["pausedTorrentCount"]+")"));
  1894. //system.updateTreeNodeText("sending",system.lang.tree.sending+(data["activeTorrentCount"]==0?"":" ("+data["activeTorrentCount"]+")"));
  1895. $("#status_downloadspeed").html(formatSize(data["downloadSpeed"], false, "speed"));
  1896. $("#status_uploadspeed").html(formatSize(data["uploadSpeed"], false, "speed"));
  1897. system.serverSessionStats = data;
  1898. if (data["torrentCount"] == 0) {
  1899. var serversNode = system.panel.left.tree("find", "servers");
  1900. if (serversNode) {
  1901. system.panel.left.tree('remove', serversNode.target);
  1902. }
  1903. system.updateTreeNodeText("torrent-all", system.lang.tree.all);
  1904. }
  1905. });
  1906. },
  1907. // Displays status information
  1908. showStatus: function (msg, outtime) {
  1909. if ($("#m_status").panel("options").collapsed) {
  1910. $("#layout_left").layout("expand", "south");
  1911. }
  1912. this.panel.status_text.show();
  1913. if (msg) {
  1914. this.panel.status_text.html(msg);
  1915. }
  1916. if (outtime == 0) {
  1917. return;
  1918. }
  1919. if (outtime == undefined) {
  1920. outtime = 3000;
  1921. }
  1922. this.panel.status_text.fadeOut(outtime, function () {
  1923. $("#layout_left").layout("collapse", "south");
  1924. });
  1925. },
  1926. // Updates the tree node text
  1927. updateTreeNodeText: function (id, text, iconCls) {
  1928. var node = this.panel.left.tree("find", id);
  1929. if (node) {
  1930. var data = {
  1931. target: node.target,
  1932. text: text
  1933. };
  1934. if (iconCls != undefined) {
  1935. data["iconCls"] = iconCls
  1936. }
  1937. this.panel.left.tree("update", data);
  1938. }
  1939. node = null;
  1940. },
  1941. // Append tree nodes
  1942. appendTreeNode: function (parentid, data) {
  1943. var parent = null;
  1944. if (typeof (parentid) == "string") {
  1945. parent = this.panel.left.tree("find", parentid);
  1946. } else
  1947. parent = parentid;
  1948. if (parent) {
  1949. this.panel.left.tree("append", {
  1950. parent: parent.target,
  1951. data: data
  1952. });
  1953. } else {
  1954. this.panel.left.tree("append", {
  1955. data: data
  1956. });
  1957. }
  1958. parent = null;
  1959. },
  1960. // Remove tree nodes
  1961. removeTreeNode: function (id) {
  1962. var node = this.panel.left.tree("find", id);
  1963. if (node) {
  1964. this.panel.left.tree("remove", node.target);
  1965. }
  1966. node = null;
  1967. },
  1968. // Load the torrent list
  1969. loadTorrentToList: function (config) {
  1970. if (!transmission.torrents.all) {
  1971. return;
  1972. }
  1973. var def = {
  1974. node: null,
  1975. page: 1
  1976. };
  1977. jQuery.extend(def, config);
  1978. if (!config.node) return;
  1979. var torrents = null;
  1980. var parent = this.panel.left.tree("getParent", config.node.target) || {
  1981. id: ""
  1982. };
  1983. var currentNodeId = this.panel.left.data("currentNodeId");
  1984. if (currentNodeId != config.node.id) {
  1985. // 当切换了导航菜单时,取消选择所有内容
  1986. this.control.torrentlist.datagrid("uncheckAll");
  1987. this.control.torrentlist.datagrid({
  1988. pageNumber: 1
  1989. });
  1990. currentNodeId = config.node.id;
  1991. }
  1992. this.panel.left.data("currentNodeId", currentNodeId);
  1993. switch (parent.id) {
  1994. case "servers":
  1995. case "btservers":
  1996. if (config.node.id=="btservers") {
  1997. torrents = transmission.torrents.btItems;
  1998. } else {
  1999. torrents = transmission.trackers[config.node.id].torrents;
  2000. }
  2001. break;
  2002. default:
  2003. switch (config.node.id) {
  2004. case "torrent-all":
  2005. case "servers":
  2006. torrents = transmission.torrents.all;
  2007. break;
  2008. case "paused":
  2009. torrents = transmission.torrents.status[transmission._status.stopped];
  2010. break;
  2011. case "sending":
  2012. torrents = transmission.torrents.status[transmission._status.seed];
  2013. break;
  2014. case "seedwait":
  2015. torrents = transmission.torrents.status[transmission._status.seedwait];
  2016. break;
  2017. case "check":
  2018. torrents = transmission.torrents.status[transmission._status.check];
  2019. break;
  2020. case "checkwait":
  2021. torrents = transmission.torrents.status[transmission._status.checkwait];
  2022. break;
  2023. case "downloading":
  2024. torrents = transmission.torrents.status[transmission._status.download];
  2025. break;
  2026. case "downloadwait":
  2027. torrents = transmission.torrents.status[transmission._status.downloadwait];
  2028. break;
  2029. case "actively":
  2030. torrents = transmission.torrents.actively;
  2031. break;
  2032. case "error":
  2033. torrents = transmission.torrents.error;
  2034. break;
  2035. case "warning":
  2036. torrents = transmission.torrents.warning;
  2037. break;
  2038. case "search-result":
  2039. torrents = transmission.torrents.searchResult;
  2040. break;
  2041. case "btservers":
  2042. torrents = transmission.torrents.btItems;
  2043. break;
  2044. default:
  2045. // Categories
  2046. if (config.node.id.indexOf("folders-") != -1) {
  2047. var folder = transmission.torrents.folders[config.node.id];
  2048. if (folder) {
  2049. if (!this.config.hideSubfolders) {
  2050. torrents = folder.torrents;
  2051. } else {
  2052. torrents = [];
  2053. for (var index = 0; index < folder.torrents.length; index++) {
  2054. var element = folder.torrents[index];
  2055. if (element.downloadDir.replace(/[\\|\/]/g,"")==config.node.path) {
  2056. torrents.push(element);
  2057. }
  2058. }
  2059. }
  2060. }
  2061. } else if (config.node.id.indexOf("label-") != -1) {
  2062. var labelIndex = parseInt(config.node.labelIndex);
  2063. torrents = [];
  2064. for (var key in transmission.torrents.all) {
  2065. var item = transmission.torrents.all[key];
  2066. var labels = this.config.labelMaps[item.hashString];
  2067. if (labels && $.inArray(labelIndex, labels)!=-1) {
  2068. torrents.push(item);
  2069. }
  2070. }
  2071. }
  2072. break;
  2073. }
  2074. break;
  2075. }
  2076. if (this.config.defaultSelectNode != config.node.id) {
  2077. this.control.torrentlist.datagrid("loadData", []);
  2078. this.config.defaultSelectNode = config.node.id;
  2079. this.saveConfig();
  2080. };
  2081. var datas = new Array();
  2082. for (var index in torrents) {
  2083. if (!torrents[index]) {
  2084. return;
  2085. }
  2086. var status = this.lang.torrent["status-text"][torrents[index].status];
  2087. // var percentDone = parseFloat(torrents[index].percentDone * 100).toFixed(2);
  2088. // // Checksum, the use of verification progress
  2089. // if (status == transmission._status.check) {
  2090. // percentDone = parseFloat(torrents[index].recheckProgress * 100).toFixed(2);
  2091. // }
  2092. if (torrents[index].error != 0) {
  2093. status = "<span class='text-status-error'>" + status + "</span>";
  2094. } else if (torrents[index].warning) {
  2095. status = "<span class='text-status-warning' title='" + torrents[index].warning + "'>" + status + "</span>";
  2096. }
  2097. var data = {};
  2098. data = $.extend(data, torrents[index]);
  2099. data.status = status;
  2100. data.statusCode = torrents[index].status;
  2101. data.completeSize = Math.max(0, torrents[index].totalSize - torrents[index].leftUntilDone);
  2102. data.leecherCount = torrents[index].leecher;
  2103. data.seederCount = torrents[index].seeder;
  2104. var labels = this.config.labelMaps[data.hashString];
  2105. if (labels) {
  2106. data.labels = labels;
  2107. }
  2108. //data.leecherCount = torrents[index].leecher;
  2109. /*
  2110. datas.push({
  2111. id:torrents[index].id
  2112. ,name:torrents[index].name
  2113. ,totalSize:torrents[index].totalSize
  2114. ,percentDone:torrents[index].percentDone
  2115. ,remainingTime:torrents[index].remainingTime
  2116. ,status:status
  2117. ,statusCode:torrents[index].status
  2118. ,addedDate:torrents[index].addedDate
  2119. ,completeSize:(torrents[index].totalSize-torrents[index].leftUntilDone)
  2120. ,rateDownload:torrents[index].rateDownload
  2121. ,rateUpload:torrents[index].rateUpload
  2122. ,leecherCount:torrents[index].leecher
  2123. ,seederCount:torrents[index].seeder
  2124. ,uploadRatio:torrents[index].uploadRatio
  2125. ,uploadedEver:torrents[index].uploadedEver
  2126. });
  2127. */
  2128. datas.push(data);
  2129. }
  2130. /*
  2131. this.panel.toolbar.find("#toolbar_start").linkbutton({disabled:true});
  2132. this.panel.toolbar.find("#toolbar_pause").linkbutton({disabled:true});
  2133. this.panel.toolbar.find("#toolbar_remove").linkbutton({disabled:true});
  2134. this.panel.toolbar.find("#toolbar_recheck").linkbutton({disabled:true});
  2135. this.panel.toolbar.find("#toolbar_changeDownloadDir").linkbutton({disabled:true});
  2136. this.panel.toolbar.find("#toolbar_morepeers").linkbutton({disabled:true});
  2137. this.panel.toolbar.find("#toolbar_queue").menubutton("disable");
  2138. */
  2139. this.updateTorrentCurrentPageDatas(datas);
  2140. this.initShiftCheck();
  2141. },
  2142. /**
  2143. * shift 键选择
  2144. */
  2145. initShiftCheck: function() {
  2146. var items = $('#m_list div.datagrid-cell-check input:checkbox');
  2147. var eventName = "click.Shift";
  2148. items.off(eventName);
  2149. var lastChecked = null;
  2150. var torrentlist = this.control.torrentlist;
  2151. items.on(eventName, function(e) {
  2152. if (!lastChecked) {
  2153. lastChecked = this;
  2154. return;
  2155. }
  2156. if (e.shiftKey) {
  2157. var start = items.index(this);
  2158. var end = items.index(lastChecked);
  2159. var checked = lastChecked.checked;
  2160. var startIndex = Math.min(start, end);
  2161. var endIndex = Math.max(start, end) + 1;
  2162. for (var index = startIndex; index < endIndex; index++) {
  2163. if (checked) {
  2164. torrentlist.datagrid("checkRow", index);
  2165. } else {
  2166. torrentlist.datagrid("uncheckRow", index);
  2167. }
  2168. }
  2169. }
  2170. lastChecked = this;
  2171. });
  2172. },
  2173. // Update torrent list current page data
  2174. updateTorrentCurrentPageDatas: function (currentTypeDatas) {
  2175. // Get the current page data
  2176. var rows = this.control.torrentlist.datagrid("getRows");
  2177. if (currentTypeDatas.length == 0 && rows.length > 0) {
  2178. this.control.torrentlist.datagrid("loadData", []);
  2179. return;
  2180. }
  2181. var _options = this.control.torrentlist.datagrid("options");
  2182. var orderField = null;
  2183. if (_options.sortName) {
  2184. orderField = _options.sortName;
  2185. var orderField_func = orderField;
  2186. currentTypeDatas = currentTypeDatas.sort(arrayObjectSort(orderField_func, _options.sortOrder));
  2187. }
  2188. if (rows.length == 0 || (currentTypeDatas.length != this.control.torrentlist.datagrid("getData").total) && currentTypeDatas.length > _options.pageSize) {
  2189. this.control.torrentlist.datagrid({
  2190. loadFilter: pagerFilter,
  2191. pageNumber: _options.pageNumber,
  2192. sortName: orderField,
  2193. sortOrder: _options.sortOrder
  2194. }).datagrid("loadData", currentTypeDatas);
  2195. return;
  2196. }
  2197. // Setting data
  2198. this.control.torrentlist.datagrid("getData").originalRows = currentTypeDatas;
  2199. var start = (_options.pageNumber - 1) * parseInt(_options.pageSize);
  2200. var end = start + parseInt(_options.pageSize);
  2201. currentTypeDatas = (currentTypeDatas.slice(start, end));
  2202. //this.debug("currentTypeDatas:",currentTypeDatas);
  2203. // Current updated torrent list
  2204. var recently = {};
  2205. //
  2206. var datas = {};
  2207. // Initializes the most recently updated data
  2208. for (var index in transmission.torrents.recently) {
  2209. var item = transmission.torrents.recently[index];
  2210. recently[item.id] = true;
  2211. item = null;
  2212. }
  2213. // Initializes the data under the current type
  2214. for (var index in currentTypeDatas) {
  2215. var item = currentTypeDatas[index];
  2216. datas[item.id] = item;
  2217. item = null;
  2218. }
  2219. //this.debug("datas:",datas);
  2220. //this.debug("recently:",recently);
  2221. //this.debug("rows:",rows);
  2222. var addedDatas = {};
  2223. // Update the changed data
  2224. for (var index = rows.length - 1; index >= 0; index--) {
  2225. var item = rows[index];
  2226. var data = datas[item.id];
  2227. if (!data) {
  2228. this.control.torrentlist.datagrid("deleteRow", index);
  2229. } else if (recently[item.id]) {
  2230. this.control.torrentlist.datagrid("updateRow", {
  2231. index: index,
  2232. row: data
  2233. });
  2234. addedDatas[item.id] = item;
  2235. }
  2236. // Removes the currently deleted torrent
  2237. else if (transmission.torrents.removed) {
  2238. if (transmission.torrents.removed.length > 0 && $.inArray(item.id, transmission.torrents.removed) != -1) {
  2239. this.control.torrentlist.datagrid("deleteRow", index);
  2240. } else {
  2241. addedDatas[item.id] = item;
  2242. }
  2243. } else {
  2244. addedDatas[item.id] = item;
  2245. }
  2246. item = null;
  2247. data = null;
  2248. }
  2249. // Appends a row that does not currently exist
  2250. for (var index in currentTypeDatas) {
  2251. var item = currentTypeDatas[index];
  2252. if (!addedDatas[item.id]) {
  2253. this.control.torrentlist.datagrid("appendRow", item);
  2254. }
  2255. }
  2256. rows = null;
  2257. recently = null;
  2258. datas = null;
  2259. },
  2260. // Gets the contents of the torrent name display area
  2261. getTorrentNameBar: function (torrent) {
  2262. var className = "";
  2263. var tip = torrent.name;
  2264. switch (torrent.status) {
  2265. case transmission._status.stopped:
  2266. className = "iconlabel icon-pause-small";
  2267. break;
  2268. case transmission._status.check:
  2269. className = "iconlabel icon-checking";
  2270. break;
  2271. case transmission._status.download:
  2272. className = "iconlabel icon-down";
  2273. break;
  2274. case transmission._status.seed:
  2275. className = "iconlabel icon-up";
  2276. break;
  2277. case transmission._status.seedwait:
  2278. case transmission._status.downloadwait:
  2279. case transmission._status.checkwait:
  2280. className = "iconlabel icon-wait";
  2281. break;
  2282. }
  2283. tip += "\n" + torrent.downloadDir;
  2284. if (torrent.warning) {
  2285. className = "iconlabel icon-warning-type1";
  2286. tip += "\n\n" + this.lang["public"]["text-info"] + ": " + torrent.warning;
  2287. }
  2288. if (torrent.error != 0) {
  2289. className = "iconlabel icon-exclamation";
  2290. tip += "\n\n" + this.lang["public"]["text-info"] + ": " + torrent.errorString;
  2291. }
  2292. return '<span class="' + className + '" title="' + tip + '">' + torrent.name + '</span>';
  2293. },
  2294. // Gets the progress bar for the specified torrent
  2295. getTorrentProgressBar: function (progress, torrent) {
  2296. var className = "";
  2297. var status = 0;
  2298. if (typeof (torrent) == "object") {
  2299. status = torrent.status;
  2300. } else {
  2301. status = torrent;
  2302. }
  2303. switch (status) {
  2304. case transmission._status.stopped:
  2305. className = "torrent-progress-stop";
  2306. break;
  2307. case transmission._status.checkwait:
  2308. case transmission._status.check:
  2309. className = "torrent-progress-check";
  2310. break;
  2311. case transmission._status.downloadwait:
  2312. case transmission._status.download:
  2313. className = "torrent-progress-download";
  2314. break;
  2315. case transmission._status.seedwait:
  2316. case transmission._status.seed:
  2317. className = "torrent-progress-seed";
  2318. break;
  2319. }
  2320. if (typeof (torrent) == "object") {
  2321. if (torrent.warning) {
  2322. className = "torrent-progress-warning";
  2323. }
  2324. if (torrent.error != 0) {
  2325. className = "torrent-progress-error";
  2326. }
  2327. }
  2328. if (status==transmission._status.check) {
  2329. // 目前只有status==_status.download时 torrent 不是对象
  2330. // 检查进度条长度保持在已完成的范围内
  2331. var percentCheckText = parseFloat(torrent.recheckProgress * 100).toFixed(2);
  2332. var percentCheckView = parseFloat(progress * torrent.recheckProgress).toFixed(2);
  2333. return '<div class="torrent-progress" title="' + progress + '%">'+
  2334. '<div class="torrent-progress-text" style="z-index:2;">' + percentCheckText + '%</div>'+
  2335. '<div class="torrent-progress-bar torrent-progress-seed" style="width:' + percentCheckView + '%;z-index:1;opacity:0.7;"></div>'+
  2336. '<div class="torrent-progress-bar ' + className + '" style="width:' + progress + '%;"></div>'+
  2337. '</div>';
  2338. }
  2339. progress = progress + "%";
  2340. return '<div class="torrent-progress" title="' + progress + '"><div class="torrent-progress-text">' + progress + '</div><div class="torrent-progress-bar ' + className + '" style="width:' + progress + ';"></div></div>';
  2341. },
  2342. // Add torrent
  2343. addTorrentsToServer: function (urls, count, autostart, savepath, labels) {
  2344. //this.config.autoReload = false;
  2345. var index = count - urls.length;
  2346. var url = urls.shift();
  2347. if (!url) {
  2348. this.showStatus(this.lang.system.status.queuefinish);
  2349. //this.config.autoReload = true;
  2350. this.getServerStatus();
  2351. if(labels != null)
  2352. system.saveConfig();
  2353. return;
  2354. }
  2355. this.showStatus(this.lang.system.status.queue + (index + 1) + "/" + (count) + "<br/>" + url, 0);
  2356. transmission.addTorrentFromUrl(url, savepath, autostart, function (data) {
  2357. system.addTorrentsToServer(urls, count, autostart, savepath, labels);
  2358. if(labels != null && data.hashString != null)
  2359. system.saveLabelsConfig(data.hashString, labels);
  2360. });
  2361. },
  2362. // Starts / pauses the selected torrent
  2363. changeSelectedTorrentStatus: function (status, button, method) {
  2364. var rows = this.control.torrentlist.datagrid("getChecked");
  2365. var ids = new Array();
  2366. if (!status) {
  2367. status = "start";
  2368. }
  2369. for (var i in rows) {
  2370. ids.push(rows[i].id);
  2371. }
  2372. if (!method) {
  2373. method = "torrent-" + status;
  2374. }
  2375. if (ids.length > 0) {
  2376. if (button) {
  2377. var icon = button.linkbutton("options").iconCls;
  2378. button.linkbutton({
  2379. disabled: true,
  2380. iconCls: "icon-loading"
  2381. });
  2382. }
  2383. transmission.exec({
  2384. method: method,
  2385. arguments: {
  2386. ids: ids
  2387. }
  2388. }, function (data) {
  2389. if (button) {
  2390. button.linkbutton({
  2391. iconCls: icon
  2392. });
  2393. }
  2394. system.control.torrentlist.datagrid("uncheckAll");
  2395. system.reloadTorrentBaseInfos();
  2396. });
  2397. }
  2398. },
  2399. // get the magnetlink of torrent
  2400. getTorrentMagnetLink: function (callback) {
  2401. var rows = this.control.torrentlist.datagrid("getChecked");
  2402. var ids = new Array();
  2403. for (var i in rows) {
  2404. ids.push(rows[i].id);
  2405. }
  2406. transmission.torrents.getMagnetLink(ids, callback);
  2407. },
  2408. // Looks for the specified torrent from the torrent list
  2409. searchTorrents: function (key) {
  2410. if (key == "") {
  2411. return;
  2412. }
  2413. var result = transmission.torrents.search(key);
  2414. if (result == null || result.length == 0) {
  2415. this.removeTreeNode("search-result");
  2416. return;
  2417. }
  2418. var node = this.panel.left.tree("find", "search-result");
  2419. var text = this.lang.tree["search-result"] + " : " + key + " (" + result.length + ")";
  2420. if (node == null) {
  2421. this.appendTreeNode("torrent-all", [{
  2422. id: "search-result",
  2423. text: text,
  2424. iconCls: "iconfont tr-icon-search"
  2425. }]);
  2426. node = this.panel.left.tree("find", "search-result");
  2427. } else {
  2428. this.panel.left.tree("update", {
  2429. target: node.target,
  2430. text: text
  2431. });
  2432. }
  2433. this.panel.left.tree("select", node.target);
  2434. },
  2435. // Get the torrent details
  2436. getTorrentInfos: function (id) {
  2437. if (!transmission.torrents.all[id]) return;
  2438. if (transmission.torrents.all[id].infoIsLoading) return;
  2439. if (this.currentTorrentId > 0 && transmission.torrents.all[this.currentTorrentId]) {
  2440. if (transmission.torrents.all[this.currentTorrentId].infoIsLoading) return;
  2441. }
  2442. this.currentTorrentId = id;
  2443. // Loads only when expanded
  2444. if (!this.panel.attribute.panel("options").collapsed) {
  2445. //this.panel.attribute.panel({iconCls:"icon-loading"});
  2446. var torrent = transmission.torrents.all[id];
  2447. torrent.infoIsLoading = true;
  2448. var fields = "fileStats,trackerStats,peers,leftUntilDone,status,rateDownload,rateUpload,uploadedEver,uploadRatio,error,errorString,pieces,pieceCount,pieceSize";
  2449. // If this is the first time to load this torrent information, load more information
  2450. if (!torrent.moreInfosTag) {
  2451. fields += ",files,trackers,comment,dateCreated,creator,downloadDir";
  2452. }
  2453. // Gets the list of files
  2454. transmission.torrents.getMoreInfos(fields, id, function (result) {
  2455. torrent.infoIsLoading = false;
  2456. //system.panel.attribute.panel({iconCls:""});
  2457. if (result == null) return;
  2458. // Merge the currently returned value to the current torrent
  2459. jQuery.extend(torrent, result[0]);
  2460. if (system.currentTorrentId == 0 || system.currentTorrentId != id) {
  2461. system.clearTorrentAttribute();
  2462. return;
  2463. }
  2464. torrent.completeSize = (torrent.totalSize - torrent.leftUntilDone);
  2465. if (("files" in torrent) && torrent.files.length > 0) {
  2466. torrent.moreInfosTag = true;
  2467. }
  2468. system.fillTorrentBaseInfos(torrent);
  2469. system.fillTorrentFileList(torrent);
  2470. system.fillTorrentServerList(torrent);
  2471. system.fillTorrentPeersList(torrent);
  2472. system.fillTorrentConfig(torrent);
  2473. transmission.torrents.all[id] = torrent;
  2474. transmission.torrents.datas[id] = torrent;
  2475. });
  2476. }
  2477. },
  2478. clearTorrentAttribute: function () {
  2479. system.panel.attribute.find("#torrent-files-table").datagrid("loadData", []);
  2480. system.panel.attribute.find("#torrent-servers-table").datagrid("loadData", []);
  2481. system.panel.attribute.find("#torrent-peers-table").datagrid("loadData", []);
  2482. system.panel.attribute.find("span[id*='torrent-attribute-value']").html("");
  2483. },
  2484. // Updates the specified current page count
  2485. updateCurrentPageDatas: function (keyField, datas, sourceTable) {
  2486. // Get the current page data
  2487. var rows = sourceTable.datagrid("getRows");
  2488. var _options = sourceTable.datagrid("options");
  2489. var orderField = null;
  2490. if (_options.sortName) {
  2491. orderField = _options.sortName;
  2492. datas = datas.sort(arrayObjectSort(orderField, _options.sortOrder));
  2493. }
  2494. var isFileTable = (sourceTable.selector.indexOf("#torrent-files-table")!=-1);
  2495. var tableData = sourceTable.datagrid("getData");
  2496. var isFileFilterMode = isFileTable && !!tableData.filterString && tableData.torrentId==system.currentTorrentId;
  2497. if (isFileFilterMode){
  2498. datas = fileFilter(datas, tableData.filterString);
  2499. }
  2500. if (isFileFilterMode==false && (rows.length == 0 || (datas.length != tableData.total))) {
  2501. sourceTable.datagrid({
  2502. loadFilter: pagerFilter,
  2503. pageNumber: 1,
  2504. sortName: orderField,
  2505. sortOrder: _options.sortOrder
  2506. }).datagrid("loadData", datas);
  2507. return;
  2508. }
  2509. // Setting data
  2510. sourceTable.datagrid("getData").originalRows = datas;
  2511. var start = (_options.pageNumber - 1) * parseInt(_options.pageSize);
  2512. var end = start + parseInt(_options.pageSize);
  2513. datas = (datas.slice(start, end));
  2514. var newDatas = {};
  2515. // Initializes the data under the current type
  2516. for (var index in datas) {
  2517. var item = datas[index];
  2518. newDatas[item[keyField]] = item;
  2519. item = null;
  2520. }
  2521. // Update the changed data
  2522. for (var index = rows.length - 1; index >= 0; index--) {
  2523. var item = rows[index];
  2524. var data = newDatas[item[keyField]];
  2525. if (data) {
  2526. sourceTable.datagrid("updateRow", {
  2527. index: index,
  2528. row: data
  2529. });
  2530. } else {
  2531. sourceTable.datagrid("deleteRow", index);
  2532. }
  2533. data = null;
  2534. item = null;
  2535. }
  2536. },
  2537. // Fill the seed with basic information
  2538. fillTorrentBaseInfos: function (torrent) {
  2539. $.each(torrent, function (key, value) {
  2540. switch (key) {
  2541. // Speed
  2542. case "rateDownload":
  2543. case "rateUpload":
  2544. value = formatSize(value, true, "speed");
  2545. break;
  2546. // Size
  2547. case "totalSize":
  2548. case "uploadedEver":
  2549. case "leftUntilDone":
  2550. case "completeSize":
  2551. value = formatSize(value);
  2552. break;
  2553. // Dates
  2554. case "addedDate":
  2555. case "dateCreated":
  2556. case "doneDate":
  2557. value = formatLongTime(value);
  2558. break;
  2559. // status
  2560. case "status":
  2561. value = system.lang.torrent["status-text"][value];
  2562. break;
  2563. // error
  2564. case "error":
  2565. if (value == 0) {
  2566. system.panel.attribute.find("#torrent-attribute-tr-error").hide();
  2567. } else {
  2568. system.panel.attribute.find("#torrent-attribute-tr-error").show();
  2569. }
  2570. break;
  2571. case "remainingTime":
  2572. if (value>=3153600000000) {
  2573. value = "∞";
  2574. } else {
  2575. value = getTotalTime(value);
  2576. }
  2577. break;
  2578. // description
  2579. case "comment":
  2580. value = system.replaceURI(value);
  2581. break;
  2582. }
  2583. system.panel.attribute.find("#torrent-attribute-value-" + key).html(value);
  2584. });
  2585. var pieces = new Base64().decode_bytes(torrent.pieces);
  2586. var piece = 0;
  2587. var pieceCount = torrent.pieceCount;
  2588. var pieceSize = torrent.pieceSize;
  2589. var piecesFlag = []; //inverted
  2590. while(piece < pieceCount) {
  2591. var bset = pieces.codePointAt(piece >> 3);
  2592. for (var test=0x80; test > 0 && piece < pieceCount; test=test>>1, ++piece) {
  2593. piecesFlag.push((bset & test)?false:true);
  2594. }
  2595. }
  2596. var MAXCELLS = 500;
  2597. var piecePerCell = parseInt((MAXCELLS-1+pieceCount)/MAXCELLS);
  2598. var cellSize = formatSize(pieceSize * piecePerCell);
  2599. var cellCount = parseInt((piecePerCell-1+pieceCount)/piecePerCell);
  2600. var cell = 0;
  2601. var cells = '';
  2602. for (var cell = 0, piece = 0; cell < cellCount; ++ cell) {
  2603. var done = piecePerCell;
  2604. for (var i=0; i<piecePerCell; ++i,++piece) {
  2605. if (piecesFlag[piece]) --done;
  2606. }
  2607. var percent = parseInt(done*100/piecePerCell);
  2608. var rate = percent/100;
  2609. var ramp = parseInt((Math.pow(128, rate)-1)*100/127)/100;
  2610. cells += ('<i style="filter:saturate(' + ramp + ')" title="'+cellSize+' x '+percent+'%"></i>');
  2611. }
  2612. system.panel.attribute.find("#torrent-attribute-pieces").html(cells);
  2613. },
  2614. // Fill the torrent with a list of files
  2615. fillTorrentFileList: function (torrent) {
  2616. var files = torrent.files;
  2617. var fileStats = torrent.fileStats;
  2618. var datas = new Array();
  2619. var namelength = torrent.name.length + 1;
  2620. for (var index in files) {
  2621. var file = files[index];
  2622. var stats = fileStats[index];
  2623. var percentDone = parseFloat(stats.bytesCompleted / file.length * 100).toFixed(2);
  2624. datas.push({
  2625. name: (file.name == torrent.name ? file.name : file.name.substr(namelength)),
  2626. index: index,
  2627. bytesCompleted: stats.bytesCompleted,
  2628. percentDone: system.getTorrentProgressBar(percentDone, transmission._status.download),
  2629. length: file.length,
  2630. wanted: system.lang.torrent.attribute["status"][stats.wanted],
  2631. priority: '<span class="iconlabel icon-flag-' + stats.priority + '">' + system.lang.torrent.attribute["priority"][stats.priority] + '</span>'
  2632. });
  2633. }
  2634. this.updateCurrentPageDatas("index", datas, system.panel.attribute.find("#torrent-files-table"));
  2635. },
  2636. // Fill in the torrent server list
  2637. fillTorrentServerList: function (torrent) {
  2638. var trackerStats = torrent.trackerStats;
  2639. var datas = new Array();
  2640. for (var index in trackerStats) {
  2641. var stats = trackerStats[index];
  2642. var rowdata = {};
  2643. for (var key in stats) {
  2644. switch (key) {
  2645. case "downloadCount":
  2646. case "leecherCount":
  2647. case "seederCount":
  2648. rowdata[key] = (stats[key] == -1 ? system.lang["public"]["text-unknown"] : stats[key]);
  2649. break;
  2650. // state
  2651. case "announceState":
  2652. rowdata[key] = system.lang.torrent.attribute["servers-fields"]["announceStateText"][stats[key]];
  2653. break;
  2654. // Dates
  2655. case "lastAnnounceTime":
  2656. case "nextAnnounceTime":
  2657. rowdata[key] = formatLongTime(stats[key]);
  2658. break;
  2659. // true/false
  2660. case "lastAnnounceSucceeded":
  2661. case "lastAnnounceTimedOut":
  2662. rowdata[key] = system.lang.torrent.attribute["status"][stats[key]];
  2663. break;
  2664. default:
  2665. rowdata[key] = stats[key];
  2666. break;
  2667. }
  2668. }
  2669. datas.push(rowdata);
  2670. }
  2671. // Replace the tracker information
  2672. transmission.torrents.addTracker(torrent);
  2673. this.updateCurrentPageDatas("id", datas, system.panel.attribute.find("#torrent-servers-table"));
  2674. //console.log("datas:",datas);
  2675. //system.panel.attribute.find("#torrent-servers-table").datagrid({loadFilter:pagerFilter,pageNumber:1}).datagrid("loadData",datas);
  2676. },
  2677. // Fill the torrent user list
  2678. fillTorrentPeersList: function (torrent) {
  2679. var peers = torrent.peers;
  2680. var datas = new Array();
  2681. for (var index in peers) {
  2682. var item = peers[index];
  2683. var rowdata = {};
  2684. for (var key in item) {
  2685. rowdata[key] = item[key];
  2686. }
  2687. if (system.config.ipInfoToken !== '' || system.config.ipInfoFlagUrl !== '') {
  2688. let flag = '';
  2689. let detail = '';
  2690. let ip = rowdata['address'];
  2691. if (system.config.ipInfoDetailUrl !== '') {
  2692. if (this.ipdetail[ip] === undefined ){
  2693. $.ajax({
  2694. type: 'GET',
  2695. url: this.expandIpInfoUrl(system.config.ipInfoDetailUrl, ip)
  2696. }).done((data) => {
  2697. if (data) {
  2698. detail = data.trim();
  2699. this.ipdetail[ip] = detail;
  2700. }
  2701. });
  2702. } else {
  2703. detail = this.ipdetail[ip];
  2704. }
  2705. }
  2706. if (this.flags[ip] === undefined) {
  2707. let url = ''
  2708. if (system.config.ipInfoFlagUrl !== '') {
  2709. url = this.expandIpInfoUrl(system.config.ipInfoFlagUrl, ip);
  2710. } else {
  2711. url = 'https://ipinfo.io/' + ip + '/country?token=' + system.config.ipInfoToken;
  2712. }
  2713. $.ajax({
  2714. type: "GET",
  2715. url: url
  2716. }).done((data) => {
  2717. if (data) {
  2718. flag = data.toLowerCase().trim();
  2719. this.flags[ip] = flag;
  2720. $("img.img_ip-"+ip.replaceAll(/[:.]+/g,'_')).attr({
  2721. src: this.rootPath + 'style/flags/' + flag + '.png',
  2722. alt: flag,
  2723. title: detail!==''? detail : flag
  2724. }).show();
  2725. }
  2726. });
  2727. } else {
  2728. flag = this.flags[ip];
  2729. }
  2730. let img = "";
  2731. if (flag) {
  2732. img = '<img src="' + this.rootPath + 'style/flags/' + flag + '.png" alt="' + flag + '" title="' + (detail!==''? detail : flag) + '"> ';
  2733. } else {
  2734. img = '<img src="" class="img_ip-'+ip.replaceAll(/[:.]+/g,'_')+'" style="display:none;"> ';
  2735. }
  2736. rowdata['address'] = img + ip;
  2737. }
  2738. // 使用同类已有的翻译文本
  2739. rowdata.isUTP = system.lang.torrent.attribute["status"][item.isUTP];
  2740. var percentDone = parseFloat(item.progress * 100).toFixed(2);
  2741. rowdata.progress = system.getTorrentProgressBar(percentDone, transmission._status.download)
  2742. datas.push(rowdata);
  2743. }
  2744. this.updateCurrentPageDatas("address", datas, system.panel.attribute.find("#torrent-peers-table"));
  2745. //console.log("datas:",datas);
  2746. //system.panel.attribute.find("#torrent-peers-table").datagrid({loadFilter:pagerFilter,pageNumber:1}).datagrid("loadData",datas);
  2747. },
  2748. // Fill torrent parameters
  2749. fillTorrentConfig: function (torrent) {
  2750. if (system.panel.attribute.find("#torrent-attribute-tabs").data("selectedIndex") != 4) {
  2751. return;
  2752. }
  2753. transmission.torrents.getConfig(torrent.id, function (result) {
  2754. if (result == null) return;
  2755. var torrent = transmission.torrents.all[system.currentTorrentId];
  2756. // Merge the currently returned value to the current torrent
  2757. jQuery.extend(torrent, result[0]);
  2758. if (system.currentTorrentId == 0) return;
  2759. $.each(result[0], function (key, value) {
  2760. var indeterminate = false;
  2761. var checked = false;
  2762. var useTag = false;
  2763. switch (key) {
  2764. //
  2765. case "seedIdleMode":
  2766. case "seedRatioMode":
  2767. if (value == 0) {
  2768. checked = false;
  2769. indeterminate = true;
  2770. }
  2771. useTag = true;
  2772. case "downloadLimited":
  2773. case "uploadLimited":
  2774. if (value == true || value == 1) {
  2775. checked = true;
  2776. }
  2777. system.panel.attribute.find("input[enabledof='" + key + "']").prop("disabled", !checked);
  2778. if (useTag) {
  2779. system.panel.attribute.find("#" + key).prop("indeterminate", indeterminate).data("_tag", value)
  2780. }
  2781. system.panel.attribute.find("#" + key).prop("checked", checked);
  2782. break;
  2783. default:
  2784. system.panel.attribute.find("#" + key).val(value);
  2785. system.panel.attribute.find("#" + key).numberspinner("setValue", value);
  2786. break;
  2787. }
  2788. });
  2789. });
  2790. },
  2791. // Set the field display format
  2792. setFieldFormat: function (field) {
  2793. if (field.formatter) {
  2794. switch (field.formatter) {
  2795. case "size":
  2796. field.formatter = function (value, row, index) {
  2797. return formatSize(value);
  2798. };
  2799. break;
  2800. case "speed":
  2801. field.formatter = function (value, row, index) {
  2802. return formatSize(value, true, "speed");
  2803. };
  2804. break;
  2805. case "longtime":
  2806. field.formatter = function (value, row, index) {
  2807. return formatLongTime(value);
  2808. };
  2809. break;
  2810. case "progress":
  2811. field.formatter = function (value, row, index) {
  2812. var percentDone = parseFloat(value * 100).toFixed(2);
  2813. return system.getTorrentProgressBar(percentDone, transmission.torrents.all[row["id"]]);
  2814. };
  2815. break;
  2816. case "_usename_":
  2817. switch (field.field) {
  2818. case "name":
  2819. field.formatter = function (value, row, index) {
  2820. return system.getTorrentNameBar(transmission.torrents.all[row["id"]]);
  2821. };
  2822. break;
  2823. }
  2824. break;
  2825. case "ratio":
  2826. field.formatter = function (value, row, index) {
  2827. var className = '';
  2828. if (parseFloat(value) < 1 && value!=-1) {
  2829. className = 'text-status-warning';
  2830. }
  2831. return '<span class="' + className + '">' + (value==-1?"∞":value) + '</span>';
  2832. };
  2833. break;
  2834. case "remainingTime":
  2835. field.formatter = function (value, row, index) {
  2836. if (value>=3153600000000) {
  2837. return "∞";
  2838. }
  2839. return getTotalTime(value);
  2840. };
  2841. break;
  2842. case "labels":
  2843. field.formatter = function(value, row, index) {
  2844. return system.formetTorrentLabels(value, row.hashString);
  2845. }
  2846. break;
  2847. case "color":
  2848. field.formatter = function(value, row, index) {
  2849. var box = $("<span class='user-label'/>").html(value).css({
  2850. "background-color": value,
  2851. "color": (getGrayLevel(value) > 0.5 ? "#000" : "#fff")
  2852. });
  2853. return box.get(0).outerHTML;
  2854. }
  2855. break;
  2856. }
  2857. }
  2858. },
  2859. // Reload the data
  2860. reloadData: function () {
  2861. if (this.popoverCount>0) {
  2862. setTimeout(function(){
  2863. system.reloadData();
  2864. }, 2000);
  2865. return;
  2866. }
  2867. this.reloadSession();
  2868. this.reloading = false;
  2869. this.getServerStatus();
  2870. this.reloading = false;
  2871. this.reloadTorrentBaseInfos();
  2872. // enable all icons
  2873. // this.checkTorrentRow("all", false);
  2874. },
  2875. // Loads the directory listing
  2876. loadFolderList: function (oldFolders) {
  2877. this.removeTreeNode("folders-loading");
  2878. // Delete the directory that does not exist
  2879. for (var index in oldFolders) {
  2880. var item = oldFolders[index];
  2881. if (item) {
  2882. system.removeTreeNode(item.nodeid);
  2883. }
  2884. }
  2885. if (transmission.downloadDirs.length == 0) {
  2886. return;
  2887. }
  2888. timedChunk(transmission.downloadDirs, this.appendFolder, this, 10, function () {
  2889. // FF browser displays the total size, will be moved down a row, so a separate treatment
  2890. // 新版本已无此问题
  2891. if ($.ua.browser.name == "Firefox" && $.ua.browser.major < 60) {
  2892. system.panel.left.find("span.nav-total-size").css({
  2893. "margin-top": "-19px"
  2894. });
  2895. }
  2896. system.initUIStatus();
  2897. });
  2898. /*
  2899. for (var index in transmission.downloadDirs)
  2900. {
  2901. var parentkey = rootkey;
  2902. var fullkey = transmission.downloadDirs[index];
  2903. }*/
  2904. },
  2905. appendFolder: function (fullkey) {
  2906. if (!fullkey) return;
  2907. var rootkey = "folders";
  2908. var parentkey = rootkey;
  2909. var folder = fullkey.replace(/\\/g,"/").split("/");
  2910. var key = rootkey + "-";
  2911. var path = "";
  2912. for (var i in folder) {
  2913. var name = folder[i];
  2914. if (name == "") {
  2915. continue;
  2916. }
  2917. //key += "--" + text.replace(/\./g,"。") + "--";
  2918. path += name;
  2919. var _key = this.B64.encode(name);
  2920. key += _key.replace(/[+|\/|=]/g,"0");
  2921. var node = this.panel.left.tree("find", key);
  2922. var folderinfos = transmission.torrents.folders[key];
  2923. if (folderinfos) {
  2924. var text = name + this.showNodeMoreInfos(folderinfos.count, folderinfos.size);
  2925. if (!node) {
  2926. this.appendTreeNode(parentkey, [{
  2927. id: key,
  2928. path: path,
  2929. downDir: fullkey,
  2930. text: text,
  2931. iconCls: "iconfont tr-icon-file"
  2932. }]);
  2933. if (parentkey != rootkey) {
  2934. node = this.panel.left.tree("find", parentkey);
  2935. this.panel.left.tree("collapse", node.target);
  2936. }
  2937. } else {
  2938. this.updateTreeNodeText(key, text);
  2939. }
  2940. parentkey = key;
  2941. } else {
  2942. this.debug("appendFolder:key", key);
  2943. this.debug("appendFolder:name", name);
  2944. this.debug("appendFolder:node", node);
  2945. }
  2946. }
  2947. },
  2948. replaceURI: function (text) {
  2949. var reg = /(http|https|ftp):\/\/([^/:]+)(:\d*)?([^# ]*)/ig;
  2950. return text.replace(reg, function (url) {
  2951. return '<a href="' + url + '" target="_blank">' + url + '</a>';
  2952. });
  2953. },
  2954. // Load the parameters from cookies
  2955. readConfig: function () {
  2956. this.readUserConfig();
  2957. // 将原来的cookies的方式改为本地存储的方式
  2958. var config = this.getStorageData(this.configHead + '.system');
  2959. if (config) {
  2960. this.config = $.extend(true, this.config, JSON.parse(config));
  2961. }
  2962. for (var key in this.storageKeys.dictionary) {
  2963. this.dictionary[key] = this.getStorageData(this.storageKeys.dictionary[key]);
  2964. }
  2965. },
  2966. // Save the parameters in cookies
  2967. saveConfig: function () {
  2968. this.setStorageData(this.configHead + '.system', JSON.stringify(this.config));
  2969. for (var key in this.storageKeys.dictionary) {
  2970. this.setStorageData(this.storageKeys.dictionary[key], this.dictionary[key]);
  2971. }
  2972. this.saveUserConfig();
  2973. },
  2974. // Save labels config for torrent if need
  2975. saveLabelsConfig: function(hash, labels){
  2976. if(system.config.nav.labels){
  2977. if (labels.length==0) {
  2978. delete system.config.labelMaps[hash];
  2979. } else {
  2980. system.config.labelMaps[hash] = labels;
  2981. }
  2982. }
  2983. },
  2984. readUserConfig: function () {
  2985. var local = window.localStorage[this.configHead];
  2986. if (local) {
  2987. var localOptions = JSON.parse(local);
  2988. this.userConfig = $.extend(true, this.userConfig, localOptions);
  2989. }
  2990. },
  2991. saveUserConfig: function () {
  2992. window.localStorage[this.configHead] = JSON.stringify(this.userConfig);
  2993. },
  2994. // Upload the torrent file
  2995. uploadTorrentFile: function (fileInputId, savePath, paused, callback) {
  2996. // Determines whether the FileReader interface is supported
  2997. if (window.FileReader) {
  2998. var files = $("input[id='" + fileInputId + "']")[0].files;
  2999. $.each(files, function (index, file) {
  3000. transmission.addTorrentFromFile(file, savePath, paused, callback, files.length);
  3001. });
  3002. } else {
  3003. alert(system.lang["public"]["text-browsers-not-support-features"]);
  3004. }
  3005. },
  3006. checkUpdate: function () {
  3007. $.ajax({
  3008. url: this.checkUpdateScript,
  3009. dataType: "json",
  3010. success: function (result) {
  3011. if (result && result.tag_name) {
  3012. var update = result.created_at.substr(0,10).replace(/-/g,"");
  3013. var version = result.tag_name;
  3014. if ($.inArray(version, system.config.ignoreVersion)!=-1) {
  3015. return;
  3016. }
  3017. if (system.codeupdate < update) {
  3018. $("#area-update-infos").show();
  3019. $("#msg-updateInfos").html(update + " -> " + result.name);
  3020. var content = $("<div/>");
  3021. var html = result.body.replace(/\r\n/g,"<br/>");
  3022. var toolbar = $("<div style='text-align:right;'/>").appendTo(content);
  3023. $('<a href="https://github.com/ronggang/transmission-web-control/releases/latest" target="_blank" class="easyui-linkbutton" data-options="iconCls:\'iconfont tr-icon-github\'"/>').html(result.name + " ("+update+")").appendTo(toolbar).linkbutton();
  3024. $("<span/>").html(" ").appendTo(toolbar);
  3025. $('<a href="https://github.com/ronggang/transmission-web-control/wiki" target="_blank" class="easyui-linkbutton" data-options="iconCls:\'iconfont tr-icon-help\'"/>').html(system.lang["public"]["text-how-to-update"]).appendTo(toolbar).linkbutton();
  3026. $("<span/>").html(" ").appendTo(toolbar);
  3027. $('<button onclick="javascript:system.addIgnoreVersion(\''+version+'\');" class="easyui-linkbutton" data-options="iconCls:\'iconfont tr-icon-cancel-checked\'"/>').html(system.lang["public"]["text-ignore-this-version"]).appendTo(toolbar).linkbutton();
  3028. $("<hr/>").appendTo(content);
  3029. $("<div/>").html(html).appendTo(content);
  3030. $('#button-download-update').webuiPopover({
  3031. content: content.html(),
  3032. backdrop: true
  3033. });
  3034. } else {
  3035. $("#area-update-infos").hide();
  3036. }
  3037. }
  3038. }
  3039. });
  3040. },
  3041. addIgnoreVersion: function(version) {
  3042. if ($.inArray(version, system.config.ignoreVersion)==-1) {
  3043. this.config.ignoreVersion.push(version);
  3044. this.saveConfig();
  3045. }
  3046. $('#button-download-update').webuiPopover("hide");
  3047. $("#area-update-infos").hide();
  3048. },
  3049. // Set the language to reload the page
  3050. changeLanguages: function (lang) {
  3051. if (lang == this.lang.name || !lang) return;
  3052. this.config.defaultLang = lang;
  3053. this.saveConfig();
  3054. location.href = "?lang=" + lang;
  3055. },
  3056. getStorageData: function (key, defaultValue) {
  3057. return (window.localStorage[key] == null ? defaultValue : window.localStorage[key]);
  3058. },
  3059. setStorageData: function (key, value) {
  3060. window.localStorage[key] = value;
  3061. },
  3062. /**
  3063. * Opens the specified template window
  3064. * 打开指定的模板
  3065. * @param config 指定参数
  3066. * type: 0 窗口,1 tooltip;默认为 0
  3067. */
  3068. openDialogFromTemplate: function (config) {
  3069. var defaultConfig = {
  3070. id: null,
  3071. options: null,
  3072. datas: null,
  3073. // 0 窗口,1 tooltip
  3074. type: 0
  3075. };
  3076. config = $.extend(true, defaultConfig, config);
  3077. if (config.id == null) return;
  3078. var dialogId = config.id;
  3079. var options = config.options;
  3080. var datas = config.datas;
  3081. var dialog = $("#" + dialogId);
  3082. if (dialog.length) {
  3083. if (datas) {
  3084. $.each(datas, function (key, value) {
  3085. dialog.data(key, value);
  3086. });
  3087. }
  3088. if (config.type==0 && dialog.attr("type")==config.type) {
  3089. dialog.dialog("open");
  3090. dialog.dialog({
  3091. content: system.templates[dialogId]
  3092. });
  3093. return;
  3094. } else {
  3095. if (system.popoverCount!=0) {
  3096. setTimeout(function(){
  3097. system.openDialogFromTemplate(config);
  3098. }, 350);
  3099. return;
  3100. }
  3101. dialog.remove();
  3102. }
  3103. }
  3104. var defaultOptions = {
  3105. title: "",
  3106. width: 100,
  3107. height: 100,
  3108. resizable: false,
  3109. cache: true,
  3110. content: system.lang.dialog["system-config"].loading,
  3111. modal: true
  3112. };
  3113. options = $.extend(true, defaultOptions, options);
  3114. dialog = $("<div/>").attr({
  3115. "id": dialogId,
  3116. "type": config.type
  3117. }).appendTo(document.body);
  3118. if (config.type==0) {
  3119. dialog.dialog(options);
  3120. } else {
  3121. dialog.css({
  3122. width: options.width,
  3123. height: options.height
  3124. }).data("popoverSource", config.source);
  3125. $(config.source).webuiPopover({
  3126. url: '#' + dialogId,
  3127. title: options.title,
  3128. width: options.width,
  3129. height: options.height -18,
  3130. padding: false,
  3131. onHide: function(e) {
  3132. $(config.source).webuiPopover("destroy");
  3133. $("#" + dialogId).remove();
  3134. $(e).remove();
  3135. system.popoverCount--;
  3136. if (config.onClose) {
  3137. config.onClose(config.source);
  3138. }
  3139. },
  3140. onShow: function() {
  3141. system.popoverCount++;
  3142. }
  3143. });
  3144. }
  3145. $.get(system.rootPath + "template/" + dialogId + ".html?time=" + (new Date()), function (data) {
  3146. system.templates[dialogId] = data;
  3147. if (datas) {
  3148. $.each(datas, function (key, value) {
  3149. $("#" + dialogId).data(key, value);
  3150. });
  3151. }
  3152. if (config.type==0) {
  3153. $("#" + dialogId).dialog({
  3154. content: data
  3155. });
  3156. } else {
  3157. dialog.html(data);
  3158. $.parser.parse("#" + dialogId);
  3159. $(config.source).webuiPopover("show");
  3160. }
  3161. });
  3162. },
  3163. // Debugging information
  3164. debug: function (label, text) {
  3165. if (window.console) {
  3166. if (window.console.log) {
  3167. window.console.log(label, text);
  3168. }
  3169. }
  3170. },
  3171. /**
  3172. * 初始化主题
  3173. */
  3174. initThemes: function () {
  3175. if (this.themes) {
  3176. $('#select-themes').combobox({
  3177. groupField: 'group',
  3178. data: this.themes,
  3179. editable: false,
  3180. panelHeight: 'auto',
  3181. onChange: function (value) {
  3182. var values = (value + ";").split(";");
  3183. var theme = values[0];
  3184. var logo = values[1] || "logo.png";
  3185. $("#styleEasyui").attr('href', 'tr-web-control/script/easyui/themes/' + theme + '/easyui.css');
  3186. $("#logo").attr("src", "tr-web-control/" + logo);
  3187. system.config.theme = value;
  3188. system.saveConfig();
  3189. },
  3190. onLoadSuccess: function () {
  3191. $(this).combobox('setValue', system.config.theme || "default");
  3192. }
  3193. });
  3194. }
  3195. },
  3196. /**
  3197. * 根据指定的文本获取有效的树形目录Key
  3198. */
  3199. getValidTreeKey: function(text) {
  3200. if (!text) return "";
  3201. var _key = this.B64.encode(text);
  3202. return _key.replace(/[+|\/|=]/g,"0");
  3203. },
  3204. expandIpInfoUrl: function (url, ip) {
  3205. if (url=='' || url==undefined) {
  3206. return '';
  3207. }
  3208. return url.replace("%ip", ip)
  3209. .replace("%lang", system.lang.name)
  3210. .replace("%hostname", document.location.hostname)
  3211. .replace("%host", document.location.host)
  3212. .replace("%protocol", document.location.protocol)
  3213. .replace("%navlang", navigator.language);
  3214. }
  3215. };
  3216. $(document).ready(function () {
  3217. // Loads the default language content
  3218. $.getJSON(system.rootPath + "i18n/en.json").done(function(result){
  3219. system.defaultLang = result;
  3220. });
  3221. // Loads a list of available languages
  3222. $.getJSON(system.rootPath + "i18n.json").done(function(result){
  3223. system.languages = result;
  3224. system.init(location.search.getQueryString("lang"), location.search.getQueryString("local"));
  3225. });
  3226. });
  3227. function fileFilter(dataRows, filterString) {
  3228. var filter = new RegExp(filterString || ".*");
  3229. var rawDataFiltered = new Array;
  3230. for (var j=0;j<dataRows.length;++j){
  3231. if (filter.test(dataRows[j].name)){
  3232. rawDataFiltered.push(dataRows[j]);
  3233. }
  3234. }
  3235. return rawDataFiltered;
  3236. }
  3237. function restoreFileFilterInputbox(defaultFilter) {
  3238. var langText = system.lang.torrent.attribute["filter-template-text"];
  3239. var filterTemplate =[{
  3240. "id":1,
  3241. "text": langText ? langText["1"] : "All",
  3242. "desc":".*"
  3243. },{
  3244. "id":2,
  3245. "text": langText ? langText["2"] : "BitComet padding file",
  3246. "desc":"____padding_file"
  3247. },{
  3248. "id":3,
  3249. "text": langText ? langText["3"] : "Unnecessary files",
  3250. "desc":"(.*\\.(url|lnk)$)|(RARBG_DO_NOT_MIRROR\\.exe)|(____padding_file)"
  3251. }];
  3252. $('<input id="torrent-files-filter-string" style="width:300px;">').insertAfter("#torrent-files-filter").combobox({
  3253. valueField: 'desc',
  3254. textField: 'desc',
  3255. panelWidth: 400,
  3256. panelHeight: 'auto',
  3257. formatter: function(row){
  3258. var s = '<span style="font-weight:bold; padding:3px;">'+row.text+'</span><br/>'+
  3259. '<span style="padding-left:10px;">'+row.desc+'</span>';
  3260. return s;
  3261. }
  3262. }).combobox("loadData", filterTemplate).combobox("setValue", defaultFilter);
  3263. }
  3264. function pagerFilter(data) {
  3265. var isFileData = false;
  3266. var filterChanged = false;
  3267. if (typeof data.length == 'number' && typeof data.splice == 'function') { // is array
  3268. data = {
  3269. total: data.length,
  3270. rows: data
  3271. }
  3272. }
  3273. isFileData = this.id=="torrent-files-table";
  3274. if (isFileData) {
  3275. var fileFilterString = $("#torrent-files-filter-string").val();
  3276. filterChanged = ( (data.filterString!==fileFilterString) ||
  3277. (data.filterString && data.originalRows.length==data.unfilteredRows.length)
  3278. );
  3279. if (filterChanged) {
  3280. data.torrentId = system.currentTorrentId;
  3281. var rawData = (data.unfilteredRows) || (data.originalRows) || (data.rows);
  3282. var rawDataFiltered = fileFilter(rawData, fileFilterString);
  3283. data.originalRows = rawDataFiltered;
  3284. data.total = rawDataFiltered.length;
  3285. if (!data.unfilteredRows) {
  3286. data.unfilteredRows = (rawData);
  3287. }
  3288. data.filterString = fileFilterString;
  3289. }
  3290. }
  3291. var dg = $(this);
  3292. var opts = dg.datagrid('options');
  3293. var pager = dg.datagrid('getPager');
  3294. var buttons = dg.data("buttons");
  3295. //system.debug("pagerFilter.buttons:",buttons);
  3296. pager.pagination({
  3297. onSelectPage: function (pageNum, pageSize) {
  3298. opts.pageNumber = pageNum;
  3299. opts.pageSize = pageSize;
  3300. pager.pagination('refresh', {
  3301. pageNumber: pageNum,
  3302. pageSize: pageSize
  3303. });
  3304. dg.datagrid('loadData', data);
  3305. },
  3306. buttons: buttons
  3307. });
  3308. if (!data.originalRows) {
  3309. data.originalRows = (data.rows);
  3310. }
  3311. var start = filterChanged ? 0 : (opts.pageNumber - 1) * parseInt(opts.pageSize);
  3312. var end = start + parseInt(opts.pageSize);
  3313. data.rows = (data.originalRows.slice(start, end));
  3314. if (buttons && buttons.length) {
  3315. for (var i=0;i<buttons.length;i++) {
  3316. var button = buttons[i];
  3317. if (button.id && button.title) {
  3318. $("#"+button.id, pager).attr("title", button.title);
  3319. }
  3320. }
  3321. }
  3322. if (isFileData) {
  3323. restoreFileFilterInputbox(fileFilterString);
  3324. }
  3325. return data;
  3326. }