converse.js 166 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783
  1. /*!
  2. * Converse.js (Web-based XMPP instant messaging client)
  3. * http://conversejs.org
  4. *
  5. * Copyright (c) 2012, Jan-Carel Brand <jc@opkode.com>
  6. * Licensed under the Mozilla Public License (MPL)
  7. */
  8. // AMD/global registrations
  9. (function (root, factory) {
  10. if (typeof define === 'function' && define.amd) {
  11. define("converse",
  12. ["converse-dependencies", "converse-templates"],
  13. function(dependencies, templates) {
  14. var otr = dependencies.otr,
  15. moment = dependencies.moment;
  16. if (typeof otr !== "undefined") {
  17. return factory(jQuery, _, otr.OTR, otr.DSA, templates, moment);
  18. } else {
  19. return factory(jQuery, _, undefined, undefined, templates, moment);
  20. }
  21. }
  22. );
  23. } else {
  24. // Browser globals
  25. // FIXME
  26. _.templateSettings = {
  27. evaluate : /\{\[([\s\S]+?)\]\}/g,
  28. interpolate : /\{\{([\s\S]+?)\}\}/g
  29. };
  30. // TODO Templates not defined
  31. root.converse = factory(jQuery, _, OTR, DSA, templates);
  32. }
  33. }(this, function ($, _, OTR, DSA, templates, moment) {
  34. "use strict";
  35. if (typeof console === "undefined" || typeof console.log === "undefined") {
  36. console = { log: function () {}, error: function () {} };
  37. }
  38. $.fn.addHyperlinks = function() {
  39. if (this.length > 0) {
  40. this.each(function(i, obj) {
  41. var x = $(obj).html();
  42. var list = x.match(/\b(https?:\/\/|www\.|https?:\/\/www\.)[^\s<]{2,200}\b/g );
  43. if (list) {
  44. for (i=0; i<list.length; i++) {
  45. var prot = list[i].indexOf('http://') === 0 || list[i].indexOf('https://') === 0 ? '' : 'http://';
  46. var escaped_url = encodeURI(decodeURI(list[i])).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
  47. x = x.replace(list[i], "<a target='_blank' href='" + prot + escaped_url + "'>"+ list[i] + "</a>" );
  48. }
  49. }
  50. $(obj).html(x);
  51. });
  52. }
  53. return this;
  54. };
  55. $.fn.addEmoticons = function() {
  56. if (converse.visible_toolbar_buttons.emoticons) {
  57. if (this.length > 0) {
  58. this.each(function(i, obj) {
  59. var text = $(obj).html();
  60. text = text.replace(/:\)/g, '<span class="emoticon icon-smiley"></span>');
  61. text = text.replace(/:\-\)/g, '<span class="emoticon icon-smiley"></span>');
  62. text = text.replace(/;\)/g, '<span class="emoticon icon-wink"></span>');
  63. text = text.replace(/;\-\)/g, '<span class="emoticon icon-wink"></span>');
  64. text = text.replace(/:D/g, '<span class="emoticon icon-grin"></span>');
  65. text = text.replace(/:\-D/g, '<span class="emoticon icon-grin"></span>');
  66. text = text.replace(/:P/g, '<span class="emoticon icon-tongue"></span>');
  67. text = text.replace(/:\-P/g, '<span class="emoticon icon-tongue"></span>');
  68. text = text.replace(/:p/g, '<span class="emoticon icon-tongue"></span>');
  69. text = text.replace(/:\-p/g, '<span class="emoticon icon-tongue"></span>');
  70. text = text.replace(/8\)/g, '<span class="emoticon icon-cool"></span>');
  71. text = text.replace(/&gt;:\)/g, '<span class="emoticon icon-evil"></span>');
  72. text = text.replace(/:S/g, '<span class="emoticon icon-confused"></span>');
  73. text = text.replace(/:\\/g, '<span class="emoticon icon-wondering"></span>');
  74. text = text.replace(/:\/ /g, '<span class="emoticon icon-wondering"></span>');
  75. text = text.replace(/&gt;:\(/g, '<span class="emoticon icon-angry"></span>');
  76. text = text.replace(/:\(/g, '<span class="emoticon icon-sad"></span>');
  77. text = text.replace(/:\-\(/g, '<span class="emoticon icon-sad"></span>');
  78. text = text.replace(/:O/g, '<span class="emoticon icon-shocked"></span>');
  79. text = text.replace(/:\-O/g, '<span class="emoticon icon-shocked"></span>');
  80. text = text.replace(/\=\-O/g, '<span class="emoticon icon-shocked"></span>');
  81. text = text.replace(/\(\^.\^\)b/g, '<span class="emoticon icon-thumbs-up"></span>');
  82. text = text.replace(/<3/g, '<span class="emoticon icon-heart"></span>');
  83. $(obj).html(text);
  84. });
  85. }
  86. }
  87. return this;
  88. };
  89. var converse = {
  90. templates: templates,
  91. emit: function(evt, data) {
  92. $(this).trigger(evt, data);
  93. },
  94. once: function(evt, handler) {
  95. $(this).one(evt, handler);
  96. },
  97. on: function(evt, handler) {
  98. $(this).bind(evt, handler);
  99. },
  100. off: function(evt, handler) {
  101. $(this).unbind(evt, handler);
  102. },
  103. refreshWebkit: function () {
  104. /* This works around a webkit bug. Refresh the browser's viewport,
  105. * otherwise chatboxes are not moved along when one is closed.
  106. */
  107. if ($.browser.webkit) {
  108. var conversejs = document.getElementById('conversejs');
  109. conversejs.style.display = 'none';
  110. conversejs.offsetHeight = conversejs.offsetHeight; // no need to store this anywhere, the reference is enough
  111. conversejs.style.display = 'block';
  112. }
  113. }
  114. };
  115. converse.initialize = function (settings, callback) {
  116. var converse = this;
  117. // Constants
  118. // ---------
  119. var UNENCRYPTED = 0;
  120. var UNVERIFIED= 1;
  121. var VERIFIED= 2;
  122. var FINISHED = 3;
  123. var KEY = {
  124. ENTER: 13
  125. };
  126. var HAS_CSPRNG = ((typeof crypto !== 'undefined') &&
  127. ((typeof crypto.randomBytes === 'function') ||
  128. (typeof crypto.getRandomValues === 'function')
  129. ));
  130. var HAS_CRYPTO = HAS_CSPRNG && (
  131. (typeof CryptoJS !== "undefined") &&
  132. (typeof OTR !== "undefined") &&
  133. (typeof DSA !== "undefined")
  134. );
  135. // Default configuration values
  136. // ----------------------------
  137. this.allow_contact_requests = true;
  138. this.allow_dragresize = true;
  139. this.allow_muc = true;
  140. this.allow_otr = true;
  141. this.animate = true;
  142. this.auto_list_rooms = false;
  143. this.auto_reconnect = true;
  144. this.auto_subscribe = false;
  145. this.bosh_service_url = undefined; // The BOSH connection manager URL.
  146. this.cache_otr_key = false;
  147. this.debug = false;
  148. this.default_box_height = 324; // The default height, in pixels, for the control box, chat boxes and chatrooms.
  149. this.enable_message_carbons = false;
  150. this.expose_rid_and_sid = false;
  151. this.forward_messages = false;
  152. this.hide_muc_server = false;
  153. this.i18n = locales.en;
  154. this.no_trimming = false; // Set to true for phantomjs tests (where browser apparently has no width)
  155. this.prebind = false;
  156. this.show_controlbox_by_default = false;
  157. this.show_only_online_users = false;
  158. this.show_toolbar = true;
  159. this.use_otr_by_default = false;
  160. this.use_vcards = true;
  161. this.visible_toolbar_buttons = {
  162. 'emoticons': true,
  163. 'call': false,
  164. 'clear': true
  165. };
  166. this.xhr_custom_status = false;
  167. this.xhr_custom_status_url = '';
  168. this.xhr_user_search = false;
  169. this.xhr_user_search_url = '';
  170. // Allow only whitelisted configuration attributes to be overwritten
  171. _.extend(this, _.pick(settings, [
  172. 'allow_contact_requests',
  173. 'allow_dragresize',
  174. 'allow_muc',
  175. 'allow_otr',
  176. 'animate',
  177. 'auto_list_rooms',
  178. 'auto_reconnect',
  179. 'auto_subscribe',
  180. 'bosh_service_url',
  181. 'cache_otr_key',
  182. 'connection',
  183. 'debug',
  184. 'default_box_height',
  185. 'enable_message_carbons',
  186. 'expose_rid_and_sid',
  187. 'forward_messages',
  188. 'fullname',
  189. 'hide_muc_server',
  190. 'i18n',
  191. 'no_trimming',
  192. 'jid',
  193. 'prebind',
  194. 'rid',
  195. 'show_controlbox_by_default',
  196. 'show_only_online_users',
  197. 'show_toolbar',
  198. 'sid',
  199. 'use_otr_by_default',
  200. 'use_vcards',
  201. 'xhr_custom_status',
  202. 'xhr_custom_status_url',
  203. 'xhr_user_search',
  204. 'xhr_user_search_url'
  205. ]));
  206. if (settings.visible_toolbar_buttons) {
  207. _.extend(
  208. this.visible_toolbar_buttons,
  209. _.pick(settings.visible_toolbar_buttons, [
  210. 'emoticons', 'call', 'clear'
  211. ]
  212. ));
  213. }
  214. $.fx.off = !this.animate;
  215. // Only allow OTR if we have the capability
  216. this.allow_otr = this.allow_otr && HAS_CRYPTO;
  217. // Only use OTR by default if allow OTR is enabled to begin with
  218. this.use_otr_by_default = this.use_otr_by_default && this.allow_otr;
  219. // Translation machinery
  220. // ---------------------
  221. var __ = $.proxy(function (str) {
  222. // Translation factory
  223. if (this.i18n === undefined) {
  224. this.i18n = locales.en;
  225. }
  226. var t = this.i18n.translate(str);
  227. if (arguments.length>1) {
  228. return t.fetch.apply(t, [].slice.call(arguments,1));
  229. } else {
  230. return t.fetch();
  231. }
  232. }, this);
  233. var ___ = function (str) {
  234. /* XXX: This is part of a hack to get gettext to scan strings to be
  235. * translated. Strings we cannot send to the function above because
  236. * they require variable interpolation and we don't yet have the
  237. * variables at scan time.
  238. *
  239. * See actionInfoMessages
  240. */
  241. return str;
  242. };
  243. // Translation aware constants
  244. // ---------------------------
  245. var OTR_CLASS_MAPPING = {};
  246. OTR_CLASS_MAPPING[UNENCRYPTED] = 'unencrypted';
  247. OTR_CLASS_MAPPING[UNVERIFIED] = 'unverified';
  248. OTR_CLASS_MAPPING[VERIFIED] = 'verified';
  249. OTR_CLASS_MAPPING[FINISHED] = 'finished';
  250. var OTR_TRANSLATED_MAPPING = {};
  251. OTR_TRANSLATED_MAPPING[UNENCRYPTED] = __('unencrypted');
  252. OTR_TRANSLATED_MAPPING[UNVERIFIED] = __('unverified');
  253. OTR_TRANSLATED_MAPPING[VERIFIED] = __('verified');
  254. OTR_TRANSLATED_MAPPING[FINISHED] = __('finished');
  255. var STATUSES = {
  256. 'dnd': __('This contact is busy'),
  257. 'online': __('This contact is online'),
  258. 'offline': __('This contact is offline'),
  259. 'unavailable': __('This contact is unavailable'),
  260. 'xa': __('This contact is away for an extended period'),
  261. 'away': __('This contact is away')
  262. };
  263. // Module-level variables
  264. // ----------------------
  265. this.callback = callback || function () {};
  266. this.initial_presence_sent = 0;
  267. this.msg_counter = 0;
  268. // Module-level functions
  269. // ----------------------
  270. this.giveFeedback = function (message, klass) {
  271. $('.conn-feedback').text(message);
  272. $('.conn-feedback').attr('class', 'conn-feedback');
  273. if (klass) {
  274. $('.conn-feedback').addClass(klass);
  275. }
  276. };
  277. this.log = function (txt, level) {
  278. if (this.debug) {
  279. if (level == 'error') {
  280. console.log('ERROR: '+txt);
  281. } else {
  282. console.log(txt);
  283. }
  284. }
  285. };
  286. this.getVCard = function (jid, callback, errback) {
  287. if (!this.use_vcards) {
  288. if (callback) {
  289. callback(jid, jid);
  290. }
  291. return;
  292. }
  293. converse.connection.vcard.get(
  294. $.proxy(function (iq) {
  295. // Successful callback
  296. var $vcard = $(iq).find('vCard');
  297. var fullname = $vcard.find('FN').text(),
  298. img = $vcard.find('BINVAL').text(),
  299. img_type = $vcard.find('TYPE').text(),
  300. url = $vcard.find('URL').text();
  301. if (jid) {
  302. var rosteritem = converse.roster.get(jid);
  303. if (rosteritem) {
  304. fullname = _.isEmpty(fullname)? rosteritem.get('fullname') || jid: fullname;
  305. rosteritem.save({
  306. 'fullname': fullname,
  307. 'image_type': img_type,
  308. 'image': img,
  309. 'url': url,
  310. 'vcard_updated': moment().format()
  311. });
  312. }
  313. }
  314. if (callback) {
  315. callback(jid, fullname, img, img_type, url);
  316. }
  317. }, this),
  318. jid,
  319. function (iq) {
  320. // Error callback
  321. var rosteritem = converse.roster.get(jid);
  322. if (rosteritem) {
  323. rosteritem.save({
  324. 'vcard_updated': moment().format()
  325. });
  326. }
  327. if (errback) {
  328. errback(iq);
  329. }
  330. }
  331. );
  332. };
  333. this.reconnect = function () {
  334. converse.giveFeedback(__('Reconnecting'), 'error');
  335. converse.emit('onReconnect');
  336. if (!converse.prebind) {
  337. this.connection.connect(
  338. this.connection.jid,
  339. this.connection.pass,
  340. function (status, condition) {
  341. converse.onConnect(status, condition, true);
  342. },
  343. this.connection.wait,
  344. this.connection.hold,
  345. this.connection.route
  346. );
  347. }
  348. };
  349. this.showLoginButton = function () {
  350. var view = converse.chatboxviews.get('controlbox');
  351. if (typeof view.loginpanel !== 'undefined') {
  352. view.loginpanel.showLoginButton();
  353. }
  354. };
  355. this.onConnect = function (status, condition, reconnect) {
  356. var $button, $form;
  357. if ((status === Strophe.Status.CONNECTED) ||
  358. (status === Strophe.Status.ATTACHED)) {
  359. if ((typeof reconnect !== 'undefined') && (reconnect)) {
  360. converse.log(status === Strophe.Status.CONNECTED ? 'Reconnected' : 'Reattached');
  361. converse.onReconnected();
  362. } else {
  363. converse.log(status === Strophe.Status.CONNECTED ? 'Connected' : 'Attached');
  364. converse.onConnected();
  365. }
  366. } else if (status === Strophe.Status.DISCONNECTED) {
  367. // TODO: Handle case where user manually logs out...
  368. converse.giveFeedback(__('Disconnected'), 'error');
  369. if (converse.auto_reconnect) {
  370. converse.reconnect();
  371. } else {
  372. converse.showLoginButton();
  373. }
  374. } else if (status === Strophe.Status.Error) {
  375. converse.showLoginButton();
  376. converse.giveFeedback(__('Error'), 'error');
  377. } else if (status === Strophe.Status.CONNECTING) {
  378. converse.giveFeedback(__('Connecting'));
  379. } else if (status === Strophe.Status.CONNFAIL) {
  380. converse.showLoginButton();
  381. converse.giveFeedback(__('Connection Failed'), 'error');
  382. } else if (status === Strophe.Status.AUTHENTICATING) {
  383. converse.giveFeedback(__('Authenticating'));
  384. } else if (status === Strophe.Status.AUTHFAIL) {
  385. converse.showLoginButton();
  386. converse.giveFeedback(__('Authentication Failed'), 'error');
  387. } else if (status === Strophe.Status.DISCONNECTING) {
  388. converse.giveFeedback(__('Disconnecting'), 'error');
  389. }
  390. };
  391. this.applyHeightResistance = function (height) {
  392. /* This method applies some resistance/gravity around the
  393. * "default_box_height". If "height" is close enough to
  394. * default_box_height, then that is returned instead.
  395. */
  396. if (typeof height === 'undefined') {
  397. return converse.default_box_height;
  398. }
  399. var resistance = 10;
  400. if ((height !== converse.default_box_height) &&
  401. (Math.abs(height - converse.default_box_height) < resistance)) {
  402. return converse.default_box_height;
  403. }
  404. return height;
  405. };
  406. this.updateMsgCounter = function () {
  407. if (this.msg_counter > 0) {
  408. if (document.title.search(/^Messages \(\d+\) /) == -1) {
  409. document.title = "Messages (" + this.msg_counter + ") " + document.title;
  410. } else {
  411. document.title = document.title.replace(/^Messages \(\d+\) /, "Messages (" + this.msg_counter + ") ");
  412. }
  413. window.blur();
  414. window.focus();
  415. } else if (document.title.search(/^Messages \(\d+\) /) != -1) {
  416. document.title = document.title.replace(/^Messages \(\d+\) /, "");
  417. }
  418. };
  419. this.incrementMsgCounter = function () {
  420. this.msg_counter += 1;
  421. this.updateMsgCounter();
  422. };
  423. this.clearMsgCounter = function () {
  424. this.msg_counter = 0;
  425. this.updateMsgCounter();
  426. };
  427. this.initStatus = function (callback) {
  428. this.xmppstatus = new this.XMPPStatus();
  429. var id = b64_sha1('converse.xmppstatus-'+this.bare_jid);
  430. this.xmppstatus.id = id; // Appears to be necessary for backbone.localStorage
  431. this.xmppstatus.localStorage = new Backbone.LocalStorage(id);
  432. this.xmppstatus.fetch({success: callback, error: callback});
  433. };
  434. this.registerRosterHandler = function () {
  435. // Register handlers that depend on the roster
  436. this.connection.roster.registerCallback(
  437. $.proxy(this.roster.rosterHandler, this.roster),
  438. null, 'presence', null);
  439. };
  440. this.registerRosterXHandler = function () {
  441. this.connection.addHandler(
  442. $.proxy(this.roster.subscribeToSuggestedItems, this.roster),
  443. 'http://jabber.org/protocol/rosterx', 'message', null);
  444. };
  445. this.registerPresenceHandler = function () {
  446. this.connection.addHandler(
  447. $.proxy(function (presence) {
  448. this.presenceHandler(presence);
  449. return true;
  450. }, this.roster), null, 'presence', null);
  451. };
  452. this.initRoster = function () {
  453. // Set up the roster
  454. this.roster = new this.RosterItems();
  455. this.roster.localStorage = new Backbone.LocalStorage(
  456. b64_sha1('converse.rosteritems-'+converse.bare_jid));
  457. this.registerRosterHandler();
  458. this.registerRosterXHandler();
  459. this.registerPresenceHandler();
  460. // Now create the view which will fetch roster items from
  461. // localStorage
  462. this.rosterview = new this.RosterView({'model':this.roster});
  463. };
  464. this.registerGlobalEventHandlers = function () {
  465. $(document).click(function() {
  466. if ($('.toggle-otr ul').is(':visible')) {
  467. $('.toggle-otr ul', this).slideUp();
  468. }
  469. if ($('.toggle-smiley ul').is(':visible')) {
  470. $('.toggle-smiley ul', this).slideUp();
  471. }
  472. });
  473. $(document).on('mousemove', $.proxy(function (ev) {
  474. if (!this.resized_chatbox || !this.allow_dragresize) { return true; }
  475. ev.preventDefault();
  476. this.resized_chatbox.resizeChatBox(ev);
  477. }, this));
  478. $(document).on('mouseup', $.proxy(function (ev) {
  479. if (!this.resized_chatbox || !this.allow_dragresize) { return true; }
  480. ev.preventDefault();
  481. var height = this.applyHeightResistance(this.resized_chatbox.height);
  482. if (this.connection) {
  483. this.resized_chatbox.model.save({'height': height});
  484. } else {
  485. this.resized_chatbox.model.set({'height': height});
  486. }
  487. this.resized_chatbox = null;
  488. }, this));
  489. $(window).on("blur focus", $.proxy(function (ev) {
  490. if ((this.windowState != ev.type) && (ev.type == 'focus')) {
  491. converse.clearMsgCounter();
  492. }
  493. this.windowState = ev.type;
  494. },this));
  495. $(window).on("resize", _.debounce($.proxy(function (ev) {
  496. this.chatboxviews.trimChats();
  497. },this), 200));
  498. };
  499. this.onReconnected = function () {
  500. // We need to re-register all the event handlers on the newly
  501. // created connection.
  502. this.initStatus($.proxy(function () {
  503. this.registerRosterXHandler();
  504. this.registerPresenceHandler();
  505. this.chatboxes.registerMessageHandler();
  506. converse.xmppstatus.sendPresence();
  507. this.giveFeedback(__('Online Contacts'));
  508. }, this));
  509. };
  510. this.enableCarbons = function () {
  511. /* Ask the XMPP server to enable Message Carbons
  512. * See XEP-0280 https://xmpp.org/extensions/xep-0280.html#enabling
  513. */
  514. if (!this.enable_message_carbons) {
  515. return;
  516. }
  517. var carbons_iq = new Strophe.Builder('iq', {
  518. from: this.connection.jid,
  519. id: 'enablecarbons',
  520. type: 'set'
  521. })
  522. .c('enable', {xmlns: 'urn:xmpp:carbons:2'});
  523. this.connection.send(carbons_iq);
  524. this.connection.addHandler(function(iq) {
  525. //TODO: check if carbons was enabled:
  526. }, null, "iq", null, "enablecarbons");
  527. };
  528. this.onConnected = function () {
  529. if (this.debug) {
  530. this.connection.xmlInput = function (body) { console.log(body); };
  531. this.connection.xmlOutput = function (body) { console.log(body); };
  532. Strophe.log = function (level, msg) { console.log(level+' '+msg); };
  533. Strophe.error = function (msg) { console.log('ERROR: '+msg); };
  534. }
  535. this.bare_jid = Strophe.getBareJidFromJid(this.connection.jid);
  536. this.domain = Strophe.getDomainFromJid(this.connection.jid);
  537. this.minimized_chats = new converse.MinimizedChats({model: this.chatboxes});
  538. this.features = new this.Features();
  539. this.enableCarbons();
  540. this.initStatus($.proxy(function () {
  541. this.initRoster();
  542. this.chatboxes.onConnected();
  543. this.connection.roster.get(function () {});
  544. this.giveFeedback(__('Online Contacts'));
  545. if (this.callback) {
  546. if (this.connection.service === 'jasmine tests') {
  547. // XXX: Call back with the internal converse object. This
  548. // object should never be exposed to production systems.
  549. // 'jasmine tests' is an invalid http bind service value,
  550. // so we're sure that this is just for tests.
  551. //
  552. // TODO: We might need to consider websockets, which
  553. // probably won't use the 'service' attr. Current
  554. // strophe.js version used by converse.js doesn't support
  555. // websockets.
  556. this.callback(this);
  557. } else {
  558. this.callback();
  559. }
  560. }
  561. }, this));
  562. converse.emit('onReady');
  563. };
  564. // Backbone Models and Views
  565. // -------------------------
  566. this.OTR = Backbone.Model.extend({
  567. // A model for managing OTR settings.
  568. getSessionPassphrase: function () {
  569. if (converse.prebind) {
  570. var key = b64_sha1(converse.connection.jid),
  571. pass = window.sessionStorage[key];
  572. if (typeof pass === 'undefined') {
  573. pass = Math.floor(Math.random()*4294967295).toString();
  574. window.sessionStorage[key] = pass;
  575. }
  576. return pass;
  577. } else {
  578. return converse.connection.pass;
  579. }
  580. },
  581. generatePrivateKey: function () {
  582. var key = new DSA();
  583. var jid = converse.connection.jid;
  584. if (converse.cache_otr_key) {
  585. var cipher = CryptoJS.lib.PasswordBasedCipher;
  586. var pass = this.getSessionPassphrase();
  587. if (typeof pass !== "undefined") {
  588. // Encrypt the key and set in sessionStorage. Also store instance tag.
  589. window.sessionStorage[b64_sha1(jid+'priv_key')] =
  590. cipher.encrypt(CryptoJS.algo.AES, key.packPrivate(), pass).toString();
  591. window.sessionStorage[b64_sha1(jid+'instance_tag')] = instance_tag;
  592. window.sessionStorage[b64_sha1(jid+'pass_check')] =
  593. cipher.encrypt(CryptoJS.algo.AES, 'match', pass).toString();
  594. }
  595. }
  596. return key;
  597. }
  598. });
  599. this.Message = Backbone.Model.extend();
  600. this.Messages = Backbone.Collection.extend({
  601. model: converse.Message
  602. });
  603. this.ChatBox = Backbone.Model.extend({
  604. initialize: function () {
  605. var height = converse.applyHeightResistance(this.get('height'));
  606. if (this.get('box_id') !== 'controlbox') {
  607. this.messages = new converse.Messages();
  608. this.messages.localStorage = new Backbone.LocalStorage(
  609. b64_sha1('converse.messages'+this.get('jid')+converse.bare_jid));
  610. this.save({
  611. 'user_id' : Strophe.getNodeFromJid(this.get('jid')),
  612. 'box_id' : b64_sha1(this.get('jid')),
  613. 'otr_status': this.get('otr_status') || UNENCRYPTED,
  614. 'minimized': this.get('minimized') || false,
  615. 'time_minimized': this.get('time_minimized') || moment(),
  616. 'time_opened': this.get('time_opened') || moment().valueOf(),
  617. 'height': height
  618. });
  619. } else {
  620. this.set({
  621. 'height': height,
  622. 'time_opened': moment(0).valueOf()
  623. });
  624. }
  625. },
  626. maximize: function () {
  627. this.save({
  628. 'minimized': false,
  629. 'time_opened': moment().valueOf()
  630. });
  631. },
  632. minimize: function () {
  633. this.save({
  634. 'minimized': true,
  635. 'time_minimized': moment().format()
  636. });
  637. },
  638. getSession: function (callback) {
  639. var cipher = CryptoJS.lib.PasswordBasedCipher;
  640. var result, pass, instance_tag, saved_key, pass_check;
  641. if (converse.cache_otr_key) {
  642. pass = converse.otr.getSessionPassphrase();
  643. if (typeof pass !== "undefined") {
  644. instance_tag = window.sessionStorage[b64_sha1(this.id+'instance_tag')];
  645. saved_key = window.sessionStorage[b64_sha1(this.id+'priv_key')];
  646. pass_check = window.sessionStorage[b64_sha1(this.connection.jid+'pass_check')];
  647. if (saved_key && instance_tag && typeof pass_check !== 'undefined') {
  648. var decrypted = cipher.decrypt(CryptoJS.algo.AES, saved_key, pass);
  649. var key = DSA.parsePrivate(decrypted.toString(CryptoJS.enc.Latin1));
  650. if (cipher.decrypt(CryptoJS.algo.AES, pass_check, pass).toString(CryptoJS.enc.Latin1) === 'match') {
  651. // Verified that the passphrase is still the same
  652. this.trigger('showHelpMessages', [__('Re-establishing encrypted session')]);
  653. callback({
  654. 'key': key,
  655. 'instance_tag': instance_tag
  656. });
  657. return; // Our work is done here
  658. }
  659. }
  660. }
  661. }
  662. // We need to generate a new key and instance tag
  663. this.trigger('showHelpMessages', [
  664. __('Generating private key.'),
  665. __('Your browser might become unresponsive.')],
  666. null,
  667. true // show spinner
  668. );
  669. setTimeout(function () {
  670. callback({
  671. 'key': converse.otr.generatePrivateKey.apply(this),
  672. 'instance_tag': OTR.makeInstanceTag()
  673. });
  674. }, 500);
  675. },
  676. updateOTRStatus: function (state) {
  677. switch (state) {
  678. case OTR.CONST.STATUS_AKE_SUCCESS:
  679. if (this.otr.msgstate === OTR.CONST.MSGSTATE_ENCRYPTED) {
  680. this.save({'otr_status': UNVERIFIED});
  681. }
  682. break;
  683. case OTR.CONST.STATUS_END_OTR:
  684. if (this.otr.msgstate === OTR.CONST.MSGSTATE_FINISHED) {
  685. this.save({'otr_status': FINISHED});
  686. } else if (this.otr.msgstate === OTR.CONST.MSGSTATE_PLAINTEXT) {
  687. this.save({'otr_status': UNENCRYPTED});
  688. }
  689. break;
  690. }
  691. },
  692. onSMP: function (type, data) {
  693. // Event handler for SMP (Socialist's Millionaire Protocol)
  694. // used by OTR (off-the-record).
  695. switch (type) {
  696. case 'question':
  697. this.otr.smpSecret(prompt(__(
  698. 'Authentication request from %1$s\n\nYour buddy is attempting to verify your identity, by asking you the question below.\n\n%2$s',
  699. [this.get('fullname'), data])));
  700. break;
  701. case 'trust':
  702. if (data === true) {
  703. this.save({'otr_status': VERIFIED});
  704. } else {
  705. this.trigger(
  706. 'showHelpMessages',
  707. [__("Could not verify this user's identify.")],
  708. 'error');
  709. this.save({'otr_status': UNVERIFIED});
  710. }
  711. break;
  712. default:
  713. throw new Error('Unknown type.');
  714. }
  715. },
  716. initiateOTR: function (query_msg) {
  717. // Sets up an OTR object through which we can send and receive
  718. // encrypted messages.
  719. //
  720. // If 'query_msg' is passed in, it means there is an alread incoming
  721. // query message from our buddy. Otherwise, it is us who will
  722. // send the query message to them.
  723. this.save({'otr_status': UNENCRYPTED});
  724. var session = this.getSession($.proxy(function (session) {
  725. this.otr = new OTR({
  726. fragment_size: 140,
  727. send_interval: 200,
  728. priv: session.key,
  729. instance_tag: session.instance_tag,
  730. debug: this.debug
  731. });
  732. this.otr.on('status', $.proxy(this.updateOTRStatus, this));
  733. this.otr.on('smp', $.proxy(this.onSMP, this));
  734. this.otr.on('ui', $.proxy(function (msg) {
  735. this.trigger('showReceivedOTRMessage', msg);
  736. }, this));
  737. this.otr.on('io', $.proxy(function (msg) {
  738. this.trigger('sendMessageStanza', msg);
  739. }, this));
  740. this.otr.on('error', $.proxy(function (msg) {
  741. this.trigger('showOTRError', msg);
  742. }, this));
  743. this.trigger('showHelpMessages', [__('Exchanging private key with buddy.')]);
  744. if (query_msg) {
  745. this.otr.receiveMsg(query_msg);
  746. } else {
  747. this.otr.sendQueryMsg();
  748. }
  749. }, this));
  750. },
  751. endOTR: function () {
  752. if (this.otr) {
  753. this.otr.endOtr();
  754. }
  755. this.save({'otr_status': UNENCRYPTED});
  756. },
  757. createMessage: function ($message) {
  758. var body = $message.children('body').text(),
  759. from = Strophe.getBareJidFromJid($message.attr('from')),
  760. composing = $message.find('composing'),
  761. delayed = $message.find('delay').length > 0,
  762. fullname = this.get('fullname'),
  763. stamp, time, sender;
  764. fullname = (_.isEmpty(fullname)? from: fullname).split(' ')[0];
  765. if (!body) {
  766. if (composing.length) {
  767. this.messages.add({
  768. fullname: fullname,
  769. sender: 'them',
  770. delayed: delayed,
  771. time: moment().format(),
  772. composing: composing.length
  773. });
  774. }
  775. } else {
  776. if (delayed) {
  777. stamp = $message.find('delay').attr('stamp');
  778. time = stamp;
  779. } else {
  780. time = moment().format();
  781. }
  782. if (from == converse.bare_jid) {
  783. sender = 'me';
  784. } else {
  785. sender = 'them';
  786. }
  787. this.messages.create({
  788. fullname: fullname,
  789. sender: sender,
  790. delayed: delayed,
  791. time: time,
  792. message: body
  793. });
  794. }
  795. },
  796. receiveMessage: function ($message) {
  797. var $body = $message.children('body');
  798. var text = ($body.length > 0 ? $body.text() : undefined);
  799. if ((!text) || (!converse.allow_otr)) {
  800. return this.createMessage($message);
  801. }
  802. if (text.match(/^\?OTRv23?/)) {
  803. this.initiateOTR(text);
  804. } else {
  805. if (_.contains([UNVERIFIED, VERIFIED], this.get('otr_status'))) {
  806. this.otr.receiveMsg(text);
  807. } else {
  808. if (text.match(/^\?OTR/)) {
  809. if (!this.otr) {
  810. this.initiateOTR(text);
  811. } else {
  812. this.otr.receiveMsg(text);
  813. }
  814. } else {
  815. // Normal unencrypted message.
  816. this.createMessage($message);
  817. }
  818. }
  819. }
  820. }
  821. });
  822. this.ChatBoxView = Backbone.View.extend({
  823. length: 200,
  824. tagName: 'div',
  825. className: 'chatbox',
  826. is_chatroom: false, // This is not a multi-user chatroom
  827. events: {
  828. 'click .close-chatbox-button': 'close',
  829. 'click .toggle-chatbox-button': 'minimize',
  830. 'keypress textarea.chat-textarea': 'keyPressed',
  831. 'click .toggle-smiley': 'toggleEmoticonMenu',
  832. 'click .toggle-smiley ul li': 'insertEmoticon',
  833. 'click .toggle-clear': 'clearMessages',
  834. 'click .toggle-otr': 'toggleOTRMenu',
  835. 'click .start-otr': 'startOTRFromToolbar',
  836. 'click .end-otr': 'endOTR',
  837. 'click .auth-otr': 'authOTR',
  838. 'click .toggle-call': 'toggleCall',
  839. 'mousedown .dragresize-tm': 'onDragResizeStart'
  840. },
  841. initialize: function (){
  842. this.model.messages.on('add', this.onMessageAdded, this);
  843. this.model.on('show', this.show, this);
  844. this.model.on('destroy', this.hide, this);
  845. this.model.on('change', this.onChange, this);
  846. this.model.on('showOTRError', this.showOTRError, this);
  847. this.model.on('buddyStartsOTR', this.buddyStartsOTR, this);
  848. this.model.on('showHelpMessages', this.showHelpMessages, this);
  849. this.model.on('sendMessageStanza', this.sendMessageStanza, this);
  850. this.model.on('showSentOTRMessage', function (text) {
  851. this.showMessage({'message': text, 'sender': 'me'});
  852. }, this);
  853. this.model.on('showReceivedOTRMessage', function (text) {
  854. this.showMessage({'message': text, 'sender': 'them'});
  855. }, this);
  856. this.updateVCard();
  857. this.$el.insertAfter(converse.chatboxviews.get("controlbox").$el);
  858. this.model.messages.fetch({add: true});
  859. this.render();
  860. if (this.model.get('minimized')) {
  861. this.hide();
  862. } else {
  863. this.show();
  864. }
  865. if ((_.contains([UNVERIFIED, VERIFIED], this.model.get('otr_status'))) || converse.use_otr_by_default) {
  866. this.model.initiateOTR();
  867. }
  868. },
  869. render: function () {
  870. this.$el.attr('id', this.model.get('box_id'))
  871. .html(converse.templates.chatbox(
  872. _.extend(this.model.toJSON(), {
  873. show_toolbar: converse.show_toolbar,
  874. label_personal_message: __('Personal message')
  875. }
  876. )
  877. )
  878. );
  879. this.renderToolbar().renderAvatar();
  880. converse.emit('onChatBoxOpened', this);
  881. setTimeout(function () {
  882. converse.refreshWebkit();
  883. }, 50);
  884. return this.showStatusMessage();
  885. },
  886. initDragResize: function () {
  887. this.prev_pageY = 0; // To store last known mouse position
  888. if (converse.connection) {
  889. this.height = this.model.get('height');
  890. }
  891. return this;
  892. },
  893. showStatusNotification: function (message, replace) {
  894. var $chat_content = this.$el.find('.chat-content');
  895. $chat_content.find('div.chat-event').remove().end()
  896. .append($('<div class="chat-event"></div>').text(message));
  897. this.scrollDown();
  898. },
  899. clearChatRoomMessages: function (ev) {
  900. ev.stopPropagation();
  901. var result = confirm(__("Are you sure you want to clear the messages from this room?"));
  902. if (result === true) {
  903. this.$el.find('.chat-content').empty();
  904. }
  905. return this;
  906. },
  907. showMessage: function (msg_dict) {
  908. var $content = this.$el.find('.chat-content'),
  909. msg_time = moment(msg_dict.time) || moment,
  910. text = msg_dict.message,
  911. match = text.match(/^\/(.*?)(?: (.*))?$/),
  912. fullname = msg_dict.fullname || this.model.get('fullname'), // XXX Perhaps always use model's?
  913. template, username;
  914. if ((match) && (match[1] === 'me')) {
  915. text = text.replace(/^\/me/, '');
  916. template = converse.templates.action;
  917. username = fullname;
  918. } else {
  919. template = converse.templates.message;
  920. username = msg_dict.sender === 'me' && __('me') || fullname;
  921. }
  922. $content.find('div.chat-event').remove();
  923. var message = template({
  924. 'sender': msg_dict.sender,
  925. 'time': msg_time.format('hh:mm'),
  926. 'username': username,
  927. 'message': '',
  928. 'extra_classes': msg_dict.delayed && 'delayed' || ''
  929. });
  930. $content.append($(message).children('.chat-message-content').first().text(text).addHyperlinks().addEmoticons().parent());
  931. this.scrollDown();
  932. },
  933. showHelpMessages: function (msgs, type, spinner) {
  934. var $chat_content = this.$el.find('.chat-content'), i,
  935. msgs_length = msgs.length;
  936. for (i=0; i<msgs_length; i++) {
  937. $chat_content.append($('<div class="chat-'+(type||'info')+'">'+msgs[i]+'</div>'));
  938. }
  939. if (spinner === true) {
  940. $chat_content.append('<span class="spinner"/>');
  941. } else if (spinner === false) {
  942. $chat_content.find('span.spinner').remove();
  943. }
  944. return this.scrollDown();
  945. },
  946. onMessageAdded: function (message) {
  947. var time = message.get('time'),
  948. times = this.model.messages.pluck('time'),
  949. previous_message, idx, this_date, prev_date, text, match;
  950. // If this message is on a different day than the one received
  951. // prior, then indicate it on the chatbox.
  952. idx = _.indexOf(times, time)-1;
  953. if (idx >= 0) {
  954. previous_message = this.model.messages.at(idx);
  955. prev_date = moment(previous_message.get('time'));
  956. if (prev_date.isBefore(time, 'day')) {
  957. this_date = moment(time);
  958. this.$el.find('.chat-content').append(converse.templates.new_day({
  959. isodate: this_date.format("YYYY-MM-DD"),
  960. datestring: this_date.format("dddd MMM Do YYYY")
  961. }));
  962. }
  963. }
  964. if (message.get('composing')) {
  965. this.showStatusNotification(message.get('fullname')+' '+'is typing');
  966. return;
  967. } else {
  968. this.showMessage(_.clone(message.attributes));
  969. }
  970. if ((message.get('sender') != 'me') && (converse.windowState == 'blur')) {
  971. converse.incrementMsgCounter();
  972. }
  973. return this.scrollDown();
  974. },
  975. sendMessageStanza: function (text) {
  976. /*
  977. * Sends the actual XML stanza to the XMPP server.
  978. */
  979. // TODO: Look in ChatPartners to see what resources we have for the recipient.
  980. // if we have one resource, we sent to only that resources, if we have multiple
  981. // we send to the bare jid.
  982. var timestamp = (new Date()).getTime();
  983. var bare_jid = this.model.get('jid');
  984. var message = $msg({from: converse.connection.jid, to: bare_jid, type: 'chat', id: timestamp})
  985. .c('body').t(text).up()
  986. .c('active', {'xmlns': 'http://jabber.org/protocol/chatstates'});
  987. converse.connection.send(message);
  988. if (converse.forward_messages) {
  989. // Forward the message, so that other connected resources are also aware of it.
  990. var forwarded = $msg({to:converse.bare_jid, type:'chat', id:timestamp})
  991. .c('forwarded', {xmlns:'urn:xmpp:forward:0'})
  992. .c('delay', {xmns:'urn:xmpp:delay',stamp:timestamp}).up()
  993. .cnode(message.tree());
  994. converse.connection.send(forwarded);
  995. }
  996. },
  997. sendMessage: function (text) {
  998. var match = text.replace(/^\s*/, "").match(/^\/(.*)\s*$/), msgs;
  999. if (match) {
  1000. if (match[1] === "clear") {
  1001. return this.clearMessages();
  1002. }
  1003. else if (match[1] === "help") {
  1004. msgs = [
  1005. '<strong>/help</strong>:'+__('Show this menu')+'',
  1006. '<strong>/me</strong>:'+__('Write in the third person')+'',
  1007. '<strong>/clear</strong>:'+__('Remove messages')+''
  1008. ];
  1009. this.showHelpMessages(msgs);
  1010. return;
  1011. } else if ((converse.allow_otr) && (match[1] === "endotr")) {
  1012. return this.endOTR();
  1013. } else if ((converse.allow_otr) && (match[1] === "otr")) {
  1014. return this.model.initiateOTR();
  1015. }
  1016. }
  1017. if (_.contains([UNVERIFIED, VERIFIED], this.model.get('otr_status'))) {
  1018. // Off-the-record encryption is active
  1019. this.model.otr.sendMsg(text);
  1020. this.model.trigger('showSentOTRMessage', text);
  1021. } else {
  1022. // We only save unencrypted messages.
  1023. var fullname = converse.xmppstatus.get('fullname');
  1024. fullname = _.isEmpty(fullname)? converse.bare_jid: fullname;
  1025. this.model.messages.create({
  1026. fullname: fullname,
  1027. sender: 'me',
  1028. time: moment().format(),
  1029. message: text
  1030. });
  1031. this.sendMessageStanza(text);
  1032. }
  1033. },
  1034. keyPressed: function (ev) {
  1035. var $textarea = $(ev.target),
  1036. message, notify, composing;
  1037. if(ev.keyCode == KEY.ENTER) {
  1038. ev.preventDefault();
  1039. message = $textarea.val();
  1040. $textarea.val('').focus();
  1041. if (message !== '') {
  1042. if (this.model.get('chatroom')) {
  1043. this.sendChatRoomMessage(message);
  1044. } else {
  1045. this.sendMessage(message);
  1046. }
  1047. converse.emit('onMessageSend', message);
  1048. }
  1049. this.$el.data('composing', false);
  1050. } else if (!this.model.get('chatroom')) {
  1051. // composing data is only for single user chat
  1052. composing = this.$el.data('composing');
  1053. if (!composing) {
  1054. if (ev.keyCode != 47) {
  1055. // We don't send composing messages if the message
  1056. // starts with forward-slash.
  1057. notify = $msg({'to':this.model.get('jid'), 'type': 'chat'})
  1058. .c('composing', {'xmlns':'http://jabber.org/protocol/chatstates'});
  1059. converse.connection.send(notify);
  1060. }
  1061. this.$el.data('composing', true);
  1062. }
  1063. }
  1064. },
  1065. onDragResizeStart: function (ev) {
  1066. if (!converse.allow_dragresize) { return true; }
  1067. // Record element attributes for mouseMove().
  1068. this.height = this.$el.children('.box-flyout').height();
  1069. converse.resized_chatbox = this;
  1070. this.prev_pageY = ev.pageY;
  1071. },
  1072. setChatBoxHeight: function (height) {
  1073. if (!this.model.get('minimized')) {
  1074. this.$el.children('.box-flyout')[0].style.height = converse.applyHeightResistance(height)+'px';
  1075. }
  1076. },
  1077. resizeChatBox: function (ev) {
  1078. var diff = ev.pageY - this.prev_pageY;
  1079. if (!diff) { return; }
  1080. this.height -= diff;
  1081. this.prev_pageY = ev.pageY;
  1082. this.setChatBoxHeight(this.height);
  1083. },
  1084. clearMessages: function (ev) {
  1085. if (ev && ev.preventDefault) {
  1086. ev.preventDefault();
  1087. }
  1088. var result = confirm(__("Are you sure you want to clear the messages from this chat box?"));
  1089. if (result === true) {
  1090. this.$el.find('.chat-content').empty();
  1091. this.model.messages.reset();
  1092. this.model.messages.localStorage._clear();
  1093. }
  1094. return this;
  1095. },
  1096. insertEmoticon: function (ev) {
  1097. ev.stopPropagation();
  1098. this.$el.find('.toggle-smiley ul').slideToggle(200);
  1099. var $textbox = this.$el.find('textarea.chat-textarea');
  1100. var value = $textbox.val();
  1101. var $target = $(ev.target);
  1102. $target = $target.is('a') ? $target : $target.children('a');
  1103. if (value && (value[value.length-1] !== ' ')) {
  1104. value = value + ' ';
  1105. }
  1106. $textbox.focus().val(value+$target.data('emoticon')+' ');
  1107. },
  1108. toggleEmoticonMenu: function (ev) {
  1109. ev.stopPropagation();
  1110. this.$el.find('.toggle-smiley ul').slideToggle(200);
  1111. },
  1112. toggleOTRMenu: function (ev) {
  1113. ev.stopPropagation();
  1114. this.$el.find('.toggle-otr ul').slideToggle(200);
  1115. },
  1116. showOTRError: function (msg) {
  1117. if (msg == 'Message cannot be sent at this time.') {
  1118. this.showHelpMessages(
  1119. [__('Your message could not be sent')], 'error');
  1120. } else if (msg == 'Received an unencrypted message.') {
  1121. this.showHelpMessages(
  1122. [__('We received an unencrypted message')], 'error');
  1123. } else if (msg == 'Received an unreadable encrypted message.') {
  1124. this.showHelpMessages(
  1125. [__('We received an unreadable encrypted message')],
  1126. 'error');
  1127. } else {
  1128. this.showHelpMessages(['Encryption error occured: '+msg], 'error');
  1129. }
  1130. console.log("OTR ERROR:"+msg);
  1131. },
  1132. buddyStartsOTR: function (ev) {
  1133. this.showHelpMessages([__('This user has requested an encrypted session.')]);
  1134. this.model.initiateOTR();
  1135. },
  1136. startOTRFromToolbar: function (ev) {
  1137. $(ev.target).parent().parent().slideUp();
  1138. ev.stopPropagation();
  1139. this.model.initiateOTR();
  1140. },
  1141. endOTR: function (ev) {
  1142. if (typeof ev !== "undefined") {
  1143. ev.preventDefault();
  1144. ev.stopPropagation();
  1145. }
  1146. this.model.endOTR();
  1147. },
  1148. authOTR: function (ev) {
  1149. var scheme = $(ev.target).data().scheme;
  1150. var result, question, answer;
  1151. if (scheme === 'fingerprint') {
  1152. result = confirm(__('Here are the fingerprints, please confirm them with %1$s, outside of this chat.\n\nFingerprint for you, %2$s: %3$s\n\nFingerprint for %1$s: %4$s\n\nIf you have confirmed that the fingerprints match, click OK, otherwise click Cancel.', [
  1153. this.model.get('fullname'),
  1154. converse.xmppstatus.get('fullname')||converse.bare_jid,
  1155. this.model.otr.priv.fingerprint(),
  1156. this.model.otr.their_priv_pk.fingerprint()
  1157. ]
  1158. ));
  1159. if (result === true) {
  1160. this.model.save({'otr_status': VERIFIED});
  1161. } else {
  1162. this.model.save({'otr_status': UNVERIFIED});
  1163. }
  1164. } else if (scheme === 'smp') {
  1165. alert(__('You will be prompted to provide a security question and then an answer to that question.\n\nYour buddy will then be prompted the same question and if they type the exact same answer (case sensitive), their identity will be verified.'));
  1166. question = prompt(__('What is your security question?'));
  1167. if (question) {
  1168. answer = prompt(__('What is the answer to the security question?'));
  1169. this.model.otr.smpSecret(answer, question);
  1170. }
  1171. } else {
  1172. this.showHelpMessages([__('Invalid authentication scheme provided')], 'error');
  1173. }
  1174. },
  1175. toggleCall: function (ev) {
  1176. ev.stopPropagation();
  1177. converse.emit('onCallButtonClicked', {
  1178. connection: converse.connection,
  1179. model: this.model
  1180. });
  1181. },
  1182. onChange: function (item, changed) {
  1183. if (_.has(item.changed, 'chat_status')) {
  1184. var chat_status = item.get('chat_status'),
  1185. fullname = item.get('fullname');
  1186. fullname = _.isEmpty(fullname)? item.get('jid'): fullname;
  1187. if (this.$el.is(':visible')) {
  1188. if (chat_status === 'offline') {
  1189. this.showStatusNotification(fullname+' '+'has gone offline');
  1190. } else if (chat_status === 'away') {
  1191. this.showStatusNotification(fullname+' '+'has gone away');
  1192. } else if ((chat_status === 'dnd')) {
  1193. this.showStatusNotification(fullname+' '+'is busy');
  1194. } else if (chat_status === 'online') {
  1195. this.$el.find('div.chat-event').remove();
  1196. }
  1197. }
  1198. converse.emit('onBuddyStatusChanged', item.attributes, item.get('chat_status'));
  1199. }
  1200. if (_.has(item.changed, 'status')) {
  1201. this.showStatusMessage();
  1202. converse.emit('onBuddyStatusMessageChanged', item.attributes, item.get('status'));
  1203. }
  1204. if (_.has(item.changed, 'image')) {
  1205. this.renderAvatar();
  1206. }
  1207. if (_.has(item.changed, 'otr_status')) {
  1208. this.renderToolbar().informOTRChange();
  1209. }
  1210. if (_.has(item.changed, 'minimized')) {
  1211. if (item.get('minimized')) {
  1212. this.hide();
  1213. } else {
  1214. this.maximize();
  1215. }
  1216. }
  1217. // TODO check for changed fullname as well
  1218. },
  1219. showStatusMessage: function (msg) {
  1220. msg = msg || this.model.get('status');
  1221. if (msg) {
  1222. this.$el.find('p.user-custom-message').text(msg).attr('title', msg);
  1223. }
  1224. return this;
  1225. },
  1226. close: function () {
  1227. if (converse.connection) {
  1228. this.model.destroy();
  1229. } else {
  1230. this.model.trigger('hide');
  1231. }
  1232. converse.emit('onChatBoxClosed', this);
  1233. return this;
  1234. },
  1235. maximize: function () {
  1236. // Restores a minimized chat box
  1237. this.$el.insertAfter(converse.chatboxviews.get("controlbox").$el).show('fast', $.proxy(function () {
  1238. converse.refreshWebkit();
  1239. this.focus();
  1240. converse.emit('onChatBoxMaximized', this);
  1241. }, this));
  1242. },
  1243. minimize: function (ev) {
  1244. // Minimizes a chat box
  1245. this.model.minimize();
  1246. this.$el.hide('fast', converse.refreshwebkit);
  1247. converse.emit('onChatBoxMinimized', this);
  1248. },
  1249. updateVCard: function () {
  1250. var jid = this.model.get('jid'),
  1251. rosteritem = converse.roster.get(jid);
  1252. if ((rosteritem) && (!rosteritem.get('vcard_updated'))) {
  1253. converse.getVCard(
  1254. jid,
  1255. $.proxy(function (jid, fullname, image, image_type, url) {
  1256. this.model.save({
  1257. 'fullname' : fullname || jid,
  1258. 'url': url,
  1259. 'image_type': image_type,
  1260. 'image': image
  1261. });
  1262. }, this),
  1263. $.proxy(function (stanza) {
  1264. converse.log("ChatBoxView.initialize: An error occured while fetching vcard");
  1265. }, this)
  1266. );
  1267. }
  1268. },
  1269. informOTRChange: function () {
  1270. var data = this.model.toJSON();
  1271. var msgs = [];
  1272. if (data.otr_status == UNENCRYPTED) {
  1273. msgs.push(__("Your messages are not encrypted anymore"));
  1274. } else if (data.otr_status == UNVERIFIED){
  1275. msgs.push(__("Your messages are now encrypted but your buddy's identity has not been verified."));
  1276. } else if (data.otr_status == VERIFIED){
  1277. msgs.push(__("Your buddy's identify has been verified."));
  1278. } else if (data.otr_status == FINISHED){
  1279. msgs.push(__("Your buddy has ended encryption on their end, you should do the same."));
  1280. }
  1281. return this.showHelpMessages(msgs, 'info', false);
  1282. },
  1283. renderToolbar: function () {
  1284. if (converse.show_toolbar) {
  1285. var data = this.model.toJSON();
  1286. if (data.otr_status == UNENCRYPTED) {
  1287. data.otr_tooltip = __('Your messages are not encrypted. Click here to enable OTR encryption.');
  1288. } else if (data.otr_status == UNVERIFIED){
  1289. data.otr_tooltip = __('Your messages are encrypted, but your buddy has not been verified.');
  1290. } else if (data.otr_status == VERIFIED){
  1291. data.otr_tooltip = __('Your messages are encrypted and your buddy verified.');
  1292. } else if (data.otr_status == FINISHED){
  1293. data.otr_tooltip = __('Your buddy has closed their end of the private session, you should do the same');
  1294. }
  1295. this.$el.find('.chat-toolbar').html(
  1296. converse.templates.toolbar(
  1297. _.extend(data, {
  1298. FINISHED: FINISHED,
  1299. UNENCRYPTED: UNENCRYPTED,
  1300. UNVERIFIED: UNVERIFIED,
  1301. VERIFIED: VERIFIED,
  1302. allow_otr: converse.allow_otr && !this.is_chatroom,
  1303. label_end_encrypted_conversation: __('End encrypted conversation'),
  1304. label_refresh_encrypted_conversation: __('Refresh encrypted conversation'),
  1305. label_start_encrypted_conversation: __('Start encrypted conversation'),
  1306. label_verify_with_fingerprints: __('Verify with fingerprints'),
  1307. label_verify_with_smp: __('Verify with SMP'),
  1308. label_whats_this: __("What\'s this?"),
  1309. otr_status_class: OTR_CLASS_MAPPING[data.otr_status],
  1310. otr_translated_status: OTR_TRANSLATED_MAPPING[data.otr_status],
  1311. show_call_button: converse.visible_toolbar_buttons.call,
  1312. show_clear_button: converse.visible_toolbar_buttons.clear,
  1313. show_emoticons: converse.visible_toolbar_buttons.emoticons
  1314. })
  1315. )
  1316. );
  1317. }
  1318. return this;
  1319. },
  1320. renderAvatar: function () {
  1321. if (!this.model.get('image')) {
  1322. return;
  1323. }
  1324. var img_src = 'data:'+this.model.get('image_type')+';base64,'+this.model.get('image'),
  1325. canvas = $('<canvas height="31px" width="31px" class="avatar"></canvas>').get(0);
  1326. if (!(canvas.getContext && canvas.getContext('2d'))) {
  1327. return this;
  1328. }
  1329. var ctx = canvas.getContext('2d');
  1330. var img = new Image(); // Create new Image object
  1331. img.onload = function() {
  1332. var ratio = img.width/img.height;
  1333. ctx.drawImage(img, 0,0, 35*ratio, 35);
  1334. };
  1335. img.src = img_src;
  1336. this.$el.find('.chat-title').before(canvas);
  1337. return this;
  1338. },
  1339. focus: function () {
  1340. this.$el.find('.chat-textarea').focus();
  1341. converse.emit('onChatBoxFocused', this);
  1342. return this;
  1343. },
  1344. hide: function () {
  1345. if (this.$el.is(':visible') && this.$el.css('opacity') == "1") {
  1346. this.$el.hide();
  1347. converse.refreshWebkit();
  1348. }
  1349. return this;
  1350. },
  1351. show: function (callback) {
  1352. if (this.$el.is(':visible') && this.$el.css('opacity') == "1") {
  1353. return this.focus();
  1354. }
  1355. this.$el.fadeIn(callback);
  1356. if (converse.connection) {
  1357. // Without a connection, we haven't yet initialized
  1358. // localstorage
  1359. this.model.save();
  1360. this.initDragResize();
  1361. }
  1362. return this;
  1363. },
  1364. scrollDown: function () {
  1365. var $content = this.$('.chat-content');
  1366. if ($content.is(':visible')) {
  1367. $content.scrollTop($content[0].scrollHeight);
  1368. }
  1369. return this;
  1370. }
  1371. });
  1372. this.ContactsPanel = Backbone.View.extend({
  1373. tagName: 'div',
  1374. className: 'controlbox-pane',
  1375. id: 'users',
  1376. events: {
  1377. 'click a.toggle-xmpp-contact-form': 'toggleContactForm',
  1378. 'submit form.add-xmpp-contact': 'addContactFromForm',
  1379. 'submit form.search-xmpp-contact': 'searchContacts',
  1380. 'click a.subscribe-to-user': 'addContactFromList'
  1381. },
  1382. initialize: function (cfg) {
  1383. cfg.$parent.append(this.$el);
  1384. this.$tabs = cfg.$parent.parent().find('#controlbox-tabs');
  1385. },
  1386. render: function () {
  1387. var markup;
  1388. var widgets = converse.templates.contacts_panel({
  1389. label_online: __('Online'),
  1390. label_busy: __('Busy'),
  1391. label_away: __('Away'),
  1392. label_offline: __('Offline')
  1393. });
  1394. this.$tabs.append(converse.templates.contacts_tab({label_contacts: __('Contacts')}));
  1395. if (converse.xhr_user_search) {
  1396. markup = converse.templates.search_contact({
  1397. label_contact_name: __('Contact name'),
  1398. label_search: __('Search')
  1399. });
  1400. } else {
  1401. markup = converse.templates.add_contact_form({
  1402. label_contact_username: __('Contact username'),
  1403. label_add: __('Add')
  1404. });
  1405. }
  1406. if (converse.allow_contact_requests) {
  1407. widgets += converse.templates.add_contact_dropdown({
  1408. label_click_to_chat: __('Click to add new chat contacts'),
  1409. label_add_contact: __('Add a contact')
  1410. });
  1411. }
  1412. this.$el.html(widgets);
  1413. this.$el.find('.search-xmpp ul').append(markup);
  1414. this.$el.append(converse.rosterview.$el);
  1415. return this;
  1416. },
  1417. toggleContactForm: function (ev) {
  1418. ev.preventDefault();
  1419. this.$el.find('.search-xmpp').toggle('fast', function () {
  1420. if ($(this).is(':visible')) {
  1421. $(this).find('input.username').focus();
  1422. }
  1423. });
  1424. },
  1425. searchContacts: function (ev) {
  1426. ev.preventDefault();
  1427. $.getJSON(xhr_user_search_url+ "?q=" + $(ev.target).find('input.username').val(), function (data) {
  1428. var $ul= $('.search-xmpp ul');
  1429. $ul.find('li.found-user').remove();
  1430. $ul.find('li.chat-info').remove();
  1431. if (!data.length) {
  1432. $ul.append('<li class="chat-info">'+__('No users found')+'</li>');
  1433. }
  1434. $(data).each(function (idx, obj) {
  1435. $ul.append(
  1436. $('<li class="found-user"></li>')
  1437. .append(
  1438. $('<a class="subscribe-to-user" href="#" title="'+__('Click to add as a chat contact')+'"></a>')
  1439. .attr('data-recipient', Strophe.escapeNode(obj.id)+'@'+converse.domain)
  1440. .text(obj.fullname)
  1441. )
  1442. );
  1443. });
  1444. });
  1445. },
  1446. addContactFromForm: function (ev) {
  1447. ev.preventDefault();
  1448. var $input = $(ev.target).find('input');
  1449. var jid = $input.val();
  1450. if (! jid) {
  1451. // this is not a valid JID
  1452. $input.addClass('error');
  1453. return;
  1454. }
  1455. this.addContact(jid);
  1456. $('.search-xmpp').hide();
  1457. },
  1458. addContactFromList: function (ev) {
  1459. ev.preventDefault();
  1460. var $target = $(ev.target),
  1461. jid = $target.attr('data-recipient'),
  1462. name = $target.text();
  1463. this.addContact(jid, name);
  1464. $target.parent().remove();
  1465. $('.search-xmpp').hide();
  1466. },
  1467. addContact: function (jid, name) {
  1468. name = _.isEmpty(name)? jid: name;
  1469. converse.connection.roster.add(jid, name, [], function (iq) {
  1470. converse.connection.roster.subscribe(jid, null, converse.xmppstatus.get('fullname'));
  1471. });
  1472. }
  1473. });
  1474. this.RoomsPanel = Backbone.View.extend({
  1475. tagName: 'div',
  1476. id: 'chatrooms',
  1477. events: {
  1478. 'submit form.add-chatroom': 'createChatRoom',
  1479. 'click input#show-rooms': 'showRooms',
  1480. 'click a.open-room': 'createChatRoom',
  1481. 'click a.room-info': 'showRoomInfo'
  1482. },
  1483. initialize: function (cfg) {
  1484. cfg.$parent.append(
  1485. this.$el.html(
  1486. converse.templates.room_panel({
  1487. 'server_input_type': converse.hide_muc_server && 'hidden' || 'text',
  1488. 'label_room_name': __('Room name'),
  1489. 'label_nickname': __('Nickname'),
  1490. 'label_server': __('Server'),
  1491. 'label_join': __('Join'),
  1492. 'label_show_rooms': __('Show rooms')
  1493. })
  1494. ).hide());
  1495. this.$tabs = cfg.$parent.parent().find('#controlbox-tabs');
  1496. this.on('update-rooms-list', function (ev) {
  1497. this.updateRoomsList();
  1498. });
  1499. converse.xmppstatus.on("change", $.proxy(function (model) {
  1500. if (!(_.has(model.changed, 'fullname'))) {
  1501. return;
  1502. }
  1503. var $nick = this.$el.find('input.new-chatroom-nick');
  1504. if (! $nick.is(':focus')) {
  1505. $nick.val(model.get('fullname'));
  1506. }
  1507. }, this));
  1508. },
  1509. render: function () {
  1510. this.$tabs.append(converse.templates.chatrooms_tab({label_rooms: __('Rooms')}));
  1511. return this;
  1512. },
  1513. informNoRoomsFound: function () {
  1514. var $available_chatrooms = this.$el.find('#available-chatrooms');
  1515. // # For translators: %1$s is a variable and will be replaced with the XMPP server name
  1516. $available_chatrooms.html('<dt>'+__('No rooms on %1$s',this.muc_domain)+'</dt>');
  1517. $('input#show-rooms').show().siblings('span.spinner').remove();
  1518. },
  1519. updateRoomsList: function (domain) {
  1520. converse.connection.muc.listRooms(
  1521. this.muc_domain,
  1522. $.proxy(function (iq) { // Success
  1523. var name, jid, i, fragment,
  1524. that = this,
  1525. $available_chatrooms = this.$el.find('#available-chatrooms');
  1526. this.rooms = $(iq).find('query').find('item');
  1527. if (this.rooms.length) {
  1528. // # For translators: %1$s is a variable and will be
  1529. // # replaced with the XMPP server name
  1530. $available_chatrooms.html('<dt>'+__('Rooms on %1$s',this.muc_domain)+'</dt>');
  1531. fragment = document.createDocumentFragment();
  1532. for (i=0; i<this.rooms.length; i++) {
  1533. name = Strophe.unescapeNode($(this.rooms[i]).attr('name')||$(this.rooms[i]).attr('jid'));
  1534. jid = $(this.rooms[i]).attr('jid');
  1535. fragment.appendChild($(
  1536. converse.templates.room_item({
  1537. 'name':name,
  1538. 'jid':jid,
  1539. 'open_title': __('Click to open this room'),
  1540. 'info_title': __('Show more information on this room')
  1541. })
  1542. )[0]);
  1543. }
  1544. $available_chatrooms.append(fragment);
  1545. $('input#show-rooms').show().siblings('span.spinner').remove();
  1546. } else {
  1547. this.informNoRoomsFound();
  1548. }
  1549. return true;
  1550. }, this),
  1551. $.proxy(function (iq) { // Failure
  1552. this.informNoRoomsFound();
  1553. }, this));
  1554. },
  1555. showRooms: function (ev) {
  1556. var $available_chatrooms = this.$el.find('#available-chatrooms');
  1557. var $server = this.$el.find('input.new-chatroom-server');
  1558. var server = $server.val();
  1559. if (!server) {
  1560. $server.addClass('error');
  1561. return;
  1562. }
  1563. this.$el.find('input.new-chatroom-name').removeClass('error');
  1564. $server.removeClass('error');
  1565. $available_chatrooms.empty();
  1566. $('input#show-rooms').hide().after('<span class="spinner"/>');
  1567. this.muc_domain = server;
  1568. this.updateRoomsList();
  1569. },
  1570. showRoomInfo: function (ev) {
  1571. var target = ev.target,
  1572. $dd = $(target).parent('dd'),
  1573. $div = $dd.find('div.room-info');
  1574. if ($div.length) {
  1575. $div.remove();
  1576. } else {
  1577. $dd.find('span.spinner').remove();
  1578. $dd.append('<span class="spinner hor_centered"/>');
  1579. converse.connection.disco.info(
  1580. $(target).attr('data-room-jid'),
  1581. null,
  1582. $.proxy(function (stanza) {
  1583. var $stanza = $(stanza);
  1584. // All MUC features found here: http://xmpp.org/registrar/disco-features.html
  1585. $dd.find('span.spinner').replaceWith(
  1586. converse.templates.room_description({
  1587. 'desc': $stanza.find('field[var="muc#roominfo_description"] value').text(),
  1588. 'occ': $stanza.find('field[var="muc#roominfo_occupants"] value').text(),
  1589. 'hidden': $stanza.find('feature[var="muc_hidden"]').length,
  1590. 'membersonly': $stanza.find('feature[var="muc_membersonly"]').length,
  1591. 'moderated': $stanza.find('feature[var="muc_moderated"]').length,
  1592. 'nonanonymous': $stanza.find('feature[var="muc_nonanonymous"]').length,
  1593. 'open': $stanza.find('feature[var="muc_open"]').length,
  1594. 'passwordprotected': $stanza.find('feature[var="muc_passwordprotected"]').length,
  1595. 'persistent': $stanza.find('feature[var="muc_persistent"]').length,
  1596. 'publicroom': $stanza.find('feature[var="muc_public"]').length,
  1597. 'semianonymous': $stanza.find('feature[var="muc_semianonymous"]').length,
  1598. 'temporary': $stanza.find('feature[var="muc_temporary"]').length,
  1599. 'unmoderated': $stanza.find('feature[var="muc_unmoderated"]').length,
  1600. 'label_desc': __('Description:'),
  1601. 'label_occ': __('Occupants:'),
  1602. 'label_features': __('Features:'),
  1603. 'label_requires_auth': __('Requires authentication'),
  1604. 'label_hidden': __('Hidden'),
  1605. 'label_requires_invite': __('Requires an invitation'),
  1606. 'label_moderated': __('Moderated'),
  1607. 'label_non_anon': __('Non-anonymous'),
  1608. 'label_open_room': __('Open room'),
  1609. 'label_permanent_room': __('Permanent room'),
  1610. 'label_public': __('Public'),
  1611. 'label_semi_anon': _('Semi-anonymous'),
  1612. 'label_temp_room': _('Temporary room'),
  1613. 'label_unmoderated': __('Unmoderated')
  1614. }));
  1615. }, this));
  1616. }
  1617. },
  1618. createChatRoom: function (ev) {
  1619. ev.preventDefault();
  1620. var name, $name,
  1621. server, $server,
  1622. jid,
  1623. $nick = this.$el.find('input.new-chatroom-nick'),
  1624. nick = $nick.val(),
  1625. chatroom;
  1626. if (!nick) { $nick.addClass('error'); }
  1627. else { $nick.removeClass('error'); }
  1628. if (ev.type === 'click') {
  1629. jid = $(ev.target).attr('data-room-jid');
  1630. } else {
  1631. $name = this.$el.find('input.new-chatroom-name');
  1632. $server= this.$el.find('input.new-chatroom-server');
  1633. server = $server.val();
  1634. name = $name.val().trim().toLowerCase();
  1635. $name.val(''); // Clear the input
  1636. if (name && server) {
  1637. jid = Strophe.escapeNode(name) + '@' + server;
  1638. $name.removeClass('error');
  1639. $server.removeClass('error');
  1640. this.muc_domain = server;
  1641. } else {
  1642. if (!name) { $name.addClass('error'); }
  1643. if (!server) { $server.addClass('error'); }
  1644. return;
  1645. }
  1646. }
  1647. if (!nick) { return; }
  1648. chatroom = converse.chatboxviews.showChat({
  1649. 'id': jid,
  1650. 'jid': jid,
  1651. 'name': Strophe.unescapeNode(Strophe.getNodeFromJid(jid)),
  1652. 'nick': nick,
  1653. 'chatroom': true,
  1654. 'box_id' : b64_sha1(jid)
  1655. });
  1656. if (!chatroom.get('connected')) {
  1657. converse.chatboxviews.get(jid).connect(null);
  1658. }
  1659. }
  1660. });
  1661. this.ControlBoxView = converse.ChatBoxView.extend({
  1662. tagName: 'div',
  1663. className: 'chatbox',
  1664. id: 'controlbox',
  1665. events: {
  1666. 'click a.close-chatbox-button': 'close',
  1667. 'click ul#controlbox-tabs li a': 'switchTab',
  1668. 'mousedown .dragresize-tm': 'onDragResizeStart'
  1669. },
  1670. initialize: function () {
  1671. this.$el.insertAfter(converse.controlboxtoggle.$el);
  1672. this.model.on('change', $.proxy(function (item, changed) {
  1673. var i;
  1674. if (_.has(item.changed, 'connected')) {
  1675. this.render();
  1676. converse.features.on('add', $.proxy(this.featureAdded, this));
  1677. // Features could have been added before the controlbox was
  1678. // initialized. Currently we're only interested in MUC
  1679. var feature = converse.features.findWhere({'var': 'http://jabber.org/protocol/muc'});
  1680. if (feature) {
  1681. this.featureAdded(feature);
  1682. }
  1683. }
  1684. }, this));
  1685. this.model.on('show', this.show, this);
  1686. this.model.on('destroy', this.hide, this);
  1687. this.model.on('hide', this.hide, this);
  1688. },
  1689. render: function () {
  1690. if ((!converse.prebind) && (!converse.connection)) {
  1691. // Add login panel if the user still has to authenticate
  1692. this.$el.html(converse.templates.controlbox(this.model.toJSON()));
  1693. this.loginpanel = new converse.LoginPanel({'$parent': this.$el.find('.controlbox-panes'), 'model': this});
  1694. this.loginpanel.render();
  1695. this.initDragResize();
  1696. } else if (!this.contactspanel) {
  1697. this.$el.html(converse.templates.controlbox(this.model.toJSON()));
  1698. this.contactspanel = new converse.ContactsPanel({'$parent': this.$el.find('.controlbox-panes')});
  1699. this.contactspanel.render();
  1700. converse.xmppstatusview = new converse.XMPPStatusView({'model': converse.xmppstatus});
  1701. converse.xmppstatusview.render();
  1702. if (converse.allow_muc) {
  1703. this.roomspanel = new converse.RoomsPanel({'$parent': this.$el.find('.controlbox-panes')});
  1704. this.roomspanel.render();
  1705. }
  1706. this.initDragResize();
  1707. }
  1708. return this;
  1709. },
  1710. hide: function (callback) {
  1711. this.$el.hide('fast', function () {
  1712. converse.refreshWebkit();
  1713. converse.emit('onChatBoxClosed', this);
  1714. converse.controlboxtoggle.show(function () {
  1715. if (typeof callback === "function") {
  1716. callback();
  1717. }
  1718. });
  1719. });
  1720. },
  1721. show: function () {
  1722. converse.controlboxtoggle.hide($.proxy(function () {
  1723. this.$el.show('fast', function () {
  1724. converse.refreshWebkit();
  1725. }.bind(this));
  1726. converse.emit('onControlBoxOpened', this);
  1727. }, this));
  1728. return this;
  1729. },
  1730. featureAdded: function (feature) {
  1731. if ((feature.get('var') == 'http://jabber.org/protocol/muc') && (converse.allow_muc)) {
  1732. this.roomspanel.muc_domain = feature.get('from');
  1733. var $server= this.$el.find('input.new-chatroom-server');
  1734. if (! $server.is(':focus')) {
  1735. $server.val(this.roomspanel.muc_domain);
  1736. }
  1737. if (converse.auto_list_rooms) {
  1738. this.roomspanel.trigger('update-rooms-list');
  1739. }
  1740. }
  1741. },
  1742. switchTab: function (ev) {
  1743. ev.preventDefault();
  1744. var $tab = $(ev.target),
  1745. $sibling = $tab.parent().siblings('li').children('a'),
  1746. $tab_panel = $($tab.attr('href'));
  1747. $($sibling.attr('href')).hide();
  1748. $sibling.removeClass('current');
  1749. $tab.addClass('current');
  1750. $tab_panel.show();
  1751. },
  1752. showHelpMessages: function (msgs) {
  1753. // Override showHelpMessages in ChatBoxView, for now do nothing.
  1754. return;
  1755. }
  1756. });
  1757. this.ChatRoomView = converse.ChatBoxView.extend({
  1758. length: 300,
  1759. tagName: 'div',
  1760. className: 'chatroom',
  1761. events: {
  1762. 'click .close-chatbox-button': 'close',
  1763. 'click .toggle-chatbox-button': 'minimize',
  1764. 'click .configure-chatroom-button': 'configureChatRoom',
  1765. 'click .toggle-smiley': 'toggleEmoticonMenu',
  1766. 'click .toggle-smiley ul li': 'insertEmoticon',
  1767. 'click .toggle-clear': 'clearChatRoomMessages',
  1768. 'keypress textarea.chat-textarea': 'keyPressed',
  1769. 'mousedown .dragresize-tm': 'onDragResizeStart'
  1770. },
  1771. is_chatroom: true,
  1772. initialize: function () {
  1773. this.connect(null);
  1774. this.model.messages.on('add', this.onMessageAdded, this);
  1775. this.model.on('change:minimized', function (item) {
  1776. if (item.get('minimized')) {
  1777. this.hide();
  1778. } else {
  1779. this.maximize();
  1780. }
  1781. }, this);
  1782. this.model.on('destroy', function (model, response, options) {
  1783. this.hide();
  1784. converse.connection.muc.leave(
  1785. this.model.get('jid'),
  1786. this.model.get('nick'),
  1787. $.proxy(this.onLeave, this),
  1788. undefined);
  1789. },
  1790. this);
  1791. this.$el.insertAfter(converse.chatboxviews.get("controlbox").$el);
  1792. this.render().model.messages.fetch({add: true});
  1793. if (this.model.get('minimized')) {
  1794. this.hide();
  1795. } else {
  1796. this.show();
  1797. }
  1798. },
  1799. render: function () {
  1800. this.$el.attr('id', this.model.get('box_id'))
  1801. .html(converse.templates.chatroom(this.model.toJSON()));
  1802. return this;
  1803. },
  1804. sendChatRoomMessage: function (body) {
  1805. var match = body.replace(/^\s*/, "").match(/^\/(.*?)(?: (.*))?$/) || [false],
  1806. $chat_content;
  1807. switch (match[1]) {
  1808. case 'msg':
  1809. // TODO: Private messages
  1810. break;
  1811. case 'clear':
  1812. this.clearChatRoomMessages();
  1813. break;
  1814. case 'topic':
  1815. converse.connection.muc.setTopic(this.model.get('jid'), match[2]);
  1816. break;
  1817. case 'kick':
  1818. converse.connection.muc.kick(this.model.get('jid'), match[2]);
  1819. break;
  1820. case 'ban':
  1821. converse.connection.muc.ban(this.model.get('jid'), match[2]);
  1822. break;
  1823. case 'op':
  1824. converse.connection.muc.op(this.model.get('jid'), match[2]);
  1825. break;
  1826. case 'deop':
  1827. converse.connection.muc.deop(this.model.get('jid'), match[2]);
  1828. break;
  1829. case 'help':
  1830. $chat_content = this.$el.find('.chat-content');
  1831. msgs = [
  1832. '<strong>/help</strong>:'+__('Show this menu')+'',
  1833. '<strong>/me</strong>:'+__('Write in the third person')+'',
  1834. '<strong>/topic</strong>:'+__('Set chatroom topic')+'',
  1835. '<strong>/kick</strong>:'+__('Kick user from chatroom')+'',
  1836. '<strong>/ban</strong>:'+__('Ban user from chatroom')+'',
  1837. '<strong>/clear</strong>:'+__('Remove messages')+''
  1838. ];
  1839. this.showHelpMessages(msgs);
  1840. break;
  1841. default:
  1842. this.last_msgid = converse.connection.muc.groupchat(this.model.get('jid'), body);
  1843. break;
  1844. }
  1845. },
  1846. renderChatArea: function () {
  1847. if (!this.$el.find('.chat-area').length) {
  1848. this.$el.find('.chat-body').empty().append(
  1849. converse.templates.chatarea({
  1850. 'show_toolbar': converse.show_toolbar,
  1851. 'label_message': __('Message')
  1852. })
  1853. );
  1854. this.renderToolbar();
  1855. }
  1856. return this;
  1857. },
  1858. connect: function (password) {
  1859. if (_.has(converse.connection.muc.rooms, this.model.get('jid'))) {
  1860. // If the room exists, it already has event listeners, so we
  1861. // doing add them again.
  1862. converse.connection.muc.join(
  1863. this.model.get('jid'), this.model.get('nick'), null, null, null, password);
  1864. } else {
  1865. converse.connection.muc.join(
  1866. this.model.get('jid'),
  1867. this.model.get('nick'),
  1868. $.proxy(this.onChatRoomMessage, this),
  1869. $.proxy(this.onChatRoomPresence, this),
  1870. $.proxy(this.onChatRoomRoster, this),
  1871. password);
  1872. }
  1873. },
  1874. onLeave: function () {
  1875. this.model.set('connected', false);
  1876. },
  1877. renderConfigurationForm: function (stanza) {
  1878. var $form= this.$el.find('form.chatroom-form'),
  1879. $stanza = $(stanza),
  1880. $fields = $stanza.find('field'),
  1881. title = $stanza.find('title').text(),
  1882. instructions = $stanza.find('instructions').text(),
  1883. i, j, options=[];
  1884. var input_types = {
  1885. 'text-private': 'password',
  1886. 'text-single': 'textline',
  1887. 'boolean': 'checkbox',
  1888. 'hidden': 'hidden',
  1889. 'list-single': 'dropdown'
  1890. };
  1891. $form.find('span.spinner').remove();
  1892. $form.append($('<legend>').text(title));
  1893. if (instructions != title) {
  1894. $form.append($('<p>').text(instructions));
  1895. }
  1896. for (i=0; i<$fields.length; i++) {
  1897. $field = $($fields[i]);
  1898. if ($field.attr('type') == 'list-single') {
  1899. options = [];
  1900. $options = $field.find('option');
  1901. for (j=0; j<$options.length; j++) {
  1902. options.push(converse.templates.select_option({
  1903. value: $($options[j]).find('value').text(),
  1904. label: $($options[j]).attr('label')
  1905. }));
  1906. }
  1907. $form.append(converse.templates.form_select({
  1908. name: $field.attr('var'),
  1909. label: $field.attr('label'),
  1910. options: options.join('')
  1911. }));
  1912. } else if ($field.attr('type') == 'boolean') {
  1913. $form.append(converse.templates.form_checkbox({
  1914. name: $field.attr('var'),
  1915. type: input_types[$field.attr('type')],
  1916. label: $field.attr('label') || '',
  1917. checked: $field.find('value').text() === "1" && 'checked="1"' || ''
  1918. }));
  1919. } else {
  1920. $form.append(converse.templates.form_input({
  1921. name: $field.attr('var'),
  1922. type: input_types[$field.attr('type')],
  1923. label: $field.attr('label') || '',
  1924. value: $field.find('value').text()
  1925. }));
  1926. }
  1927. }
  1928. $form.append('<input type="submit" value="'+__('Save')+'"/>');
  1929. $form.append('<input type="button" value="'+__('Cancel')+'"/>');
  1930. $form.on('submit', $.proxy(this.saveConfiguration, this));
  1931. $form.find('input[type=button]').on('click', $.proxy(this.cancelConfiguration, this));
  1932. },
  1933. saveConfiguration: function (ev) {
  1934. ev.preventDefault();
  1935. var that = this;
  1936. var $inputs = $(ev.target).find(':input:not([type=button]):not([type=submit])'),
  1937. count = $inputs.length,
  1938. configArray = [];
  1939. $inputs.each(function () {
  1940. var $input = $(this), value;
  1941. if ($input.is('[type=checkbox]')) {
  1942. value = $input.is(':checked') && 1 || 0;
  1943. } else {
  1944. value = $input.val();
  1945. }
  1946. var cnode = $(converse.templates.field({
  1947. name: $input.attr('name'),
  1948. value: value
  1949. }))[0];
  1950. configArray.push(cnode);
  1951. if (!--count) {
  1952. converse.connection.muc.saveConfiguration(
  1953. that.model.get('jid'),
  1954. configArray,
  1955. $.proxy(that.onConfigSaved, that),
  1956. $.proxy(that.onErrorConfigSaved, that)
  1957. );
  1958. }
  1959. });
  1960. this.$el.find('div.chatroom-form-container').hide(
  1961. function () {
  1962. $(this).remove();
  1963. that.$el.find('.chat-area').show();
  1964. that.$el.find('.participants').show();
  1965. });
  1966. },
  1967. onConfigSaved: function (stanza) {
  1968. // XXX
  1969. },
  1970. onErrorConfigSaved: function (stanza) {
  1971. this.showStatusNotification(__("An error occurred while trying to save the form."));
  1972. },
  1973. cancelConfiguration: function (ev) {
  1974. ev.preventDefault();
  1975. var that = this;
  1976. this.$el.find('div.chatroom-form-container').hide(
  1977. function () {
  1978. $(this).remove();
  1979. that.$el.find('.chat-area').show();
  1980. that.$el.find('.participants').show();
  1981. });
  1982. },
  1983. configureChatRoom: function (ev) {
  1984. ev.preventDefault();
  1985. if (this.$el.find('div.chatroom-form-container').length) {
  1986. return;
  1987. }
  1988. this.$el.find('.chat-area').hide();
  1989. this.$el.find('.participants').hide();
  1990. this.$el.find('.chat-body').append(
  1991. $('<div class="chatroom-form-container">'+
  1992. '<form class="chatroom-form">'+
  1993. '<span class="spinner centered"/>'+
  1994. '</form>'+
  1995. '</div>'));
  1996. converse.connection.muc.configure(
  1997. this.model.get('jid'),
  1998. $.proxy(this.renderConfigurationForm, this)
  1999. );
  2000. },
  2001. submitPassword: function (ev) {
  2002. ev.preventDefault();
  2003. var password = this.$el.find('.chatroom-form').find('input[type=password]').val();
  2004. this.$el.find('.chatroom-form-container').replaceWith(
  2005. '<span class="spinner centered"/>');
  2006. this.connect(password);
  2007. },
  2008. renderPasswordForm: function () {
  2009. this.$el.find('span.centered.spinner').remove();
  2010. this.$el.find('.chat-body').append(
  2011. $('<div class="chatroom-form-container">'+
  2012. '<form class="chatroom-form">'+
  2013. '<legend>'+__('This chatroom requires a password')+'</legend>' +
  2014. '<label>'+__('Password: ')+'<input type="password" name="password"/></label>' +
  2015. '<input type="submit" value="'+__('Submit')+'/>' +
  2016. '</form>'+
  2017. '</div>'));
  2018. this.$el.find('.chatroom-form').on('submit', $.proxy(this.submitPassword, this));
  2019. },
  2020. showDisconnectMessage: function (msg) {
  2021. this.$el.find('.chat-area').remove();
  2022. this.$el.find('.participants').remove();
  2023. this.$el.find('span.centered.spinner').remove();
  2024. this.$el.find('.chat-body').append($('<p>'+msg+'</p>'));
  2025. },
  2026. infoMessages: {
  2027. 100: __('This room is not anonymous'),
  2028. 102: __('This room now shows unavailable members'),
  2029. 103: __('This room does not show unavailable members'),
  2030. 104: __('Non-privacy-related room configuration has changed'),
  2031. 170: __('Room logging is now enabled'),
  2032. 171: __('Room logging is now disabled'),
  2033. 172: __('This room is now non-anonymous'),
  2034. 173: __('This room is now semi-anonymous'),
  2035. 174: __('This room is now fully-anonymous'),
  2036. 201: __('A new room has been created'),
  2037. 210: __('Your nickname has been changed')
  2038. },
  2039. actionInfoMessages: {
  2040. /* XXX: Note the triple underscore function and not double
  2041. * underscore.
  2042. *
  2043. * This is a hack. We can't pass the strings to __ because we
  2044. * don't yet know what the variable to interpolate is.
  2045. *
  2046. * Triple underscore will just return the string again, but we
  2047. * can then at least tell gettext to scan for it so that these
  2048. * strings are picked up by the translation machinery.
  2049. */
  2050. 301: ___("<strong>%1$s</strong> has been banned"),
  2051. 307: ___("<strong>%1$s</strong> has been kicked out"),
  2052. 321: ___("<strong>%1$s</strong> has been removed because of an affiliation change"),
  2053. 322: ___("<strong>%1$s</strong> has been removed for not being a member")
  2054. },
  2055. disconnectMessages: {
  2056. 301: __('You have been banned from this room'),
  2057. 307: __('You have been kicked from this room'),
  2058. 321: __("You have been removed from this room because of an affiliation change"),
  2059. 322: __("You have been removed from this room because the room has changed to members-only and you're not a member"),
  2060. 332: __("You have been removed from this room because the MUC (Multi-user chat) service is being shut down.")
  2061. },
  2062. showStatusMessages: function ($el, is_self) {
  2063. /* Check for status codes and communicate their purpose to the user
  2064. * See: http://xmpp.org/registrar/mucstatus.html
  2065. */
  2066. var $chat_content = this.$el.find('.chat-content'),
  2067. $stats = $el.find('status'),
  2068. disconnect_msgs = [],
  2069. info_msgs = [],
  2070. action_msgs = [],
  2071. msgs, i;
  2072. for (i=0; i<$stats.length; i++) {
  2073. var stat = $stats[i].getAttribute('code');
  2074. if (is_self) {
  2075. if (_.contains(_.keys(this.disconnectMessages), stat)) {
  2076. disconnect_msgs.push(this.disconnectMessages[stat]);
  2077. }
  2078. } else {
  2079. if (_.contains(_.keys(this.infoMessages), stat)) {
  2080. info_msgs.push(this.infoMessages[stat]);
  2081. } else if (_.contains(_.keys(this.actionInfoMessages), stat)) {
  2082. action_msgs.push(
  2083. __(this.actionInfoMessages[stat], Strophe.unescapeNode(Strophe.getResourceFromJid($el.attr('from'))))
  2084. );
  2085. }
  2086. }
  2087. }
  2088. if (disconnect_msgs.length > 0) {
  2089. for (i=0; i<disconnect_msgs.length; i++) {
  2090. this.showDisconnectMessage(disconnect_msgs[i]);
  2091. }
  2092. this.model.set('connected', false);
  2093. return;
  2094. }
  2095. this.renderChatArea();
  2096. for (i=0; i<info_msgs.length; i++) {
  2097. $chat_content.append(converse.templates.info({message: info_msgs[i]}));
  2098. }
  2099. for (i=0; i<action_msgs.length; i++) {
  2100. $chat_content.append(converse.templates.info({message: action_msgs[i]}));
  2101. }
  2102. return this.scrollDown();
  2103. },
  2104. showErrorMessage: function ($error, room) {
  2105. // We didn't enter the room, so we must remove it from the MUC
  2106. // add-on
  2107. delete converse.connection.muc[room.name];
  2108. if ($error.attr('type') == 'auth') {
  2109. if ($error.find('not-authorized').length) {
  2110. this.renderPasswordForm();
  2111. } else if ($error.find('registration-required').length) {
  2112. this.showDisconnectMessage(__('You are not on the member list of this room'));
  2113. } else if ($error.find('forbidden').length) {
  2114. this.showDisconnectMessage(__('You have been banned from this room'));
  2115. }
  2116. } else if ($error.attr('type') == 'modify') {
  2117. if ($error.find('jid-malformed').length) {
  2118. this.showDisconnectMessage(__('No nickname was specified'));
  2119. }
  2120. } else if ($error.attr('type') == 'cancel') {
  2121. if ($error.find('not-allowed').length) {
  2122. this.showDisconnectMessage(__('You are not allowed to create new rooms'));
  2123. } else if ($error.find('not-acceptable').length) {
  2124. this.showDisconnectMessage(__("Your nickname doesn't conform to this room's policies"));
  2125. } else if ($error.find('conflict').length) {
  2126. this.showDisconnectMessage(__("Your nickname is already taken"));
  2127. } else if ($error.find('item-not-found').length) {
  2128. this.showDisconnectMessage(__("This room does not (yet) exist"));
  2129. } else if ($error.find('service-unavailable').length) {
  2130. this.showDisconnectMessage(__("This room has reached it's maximum number of occupants"));
  2131. }
  2132. }
  2133. },
  2134. onChatRoomPresence: function (presence, room) {
  2135. var nick = room.nick,
  2136. $presence = $(presence),
  2137. from = $presence.attr('from'),
  2138. is_self = ($presence.find("status[code='110']").length) || (from == room.name+'/'+Strophe.escapeNode(nick)),
  2139. $item;
  2140. if ($presence.attr('type') === 'error') {
  2141. this.model.set('connected', false);
  2142. this.showErrorMessage($presence.find('error'), room);
  2143. } else {
  2144. this.model.set('connected', true);
  2145. this.showStatusMessages($presence, is_self);
  2146. if (!this.model.get('connected')) {
  2147. return true;
  2148. }
  2149. if ($presence.find("status[code='201']").length) {
  2150. // This is a new chatroom. We create an instant
  2151. // chatroom, and let the user manually set any
  2152. // configuration setting.
  2153. converse.connection.muc.createInstantRoom(room.name);
  2154. }
  2155. if (is_self) {
  2156. $item = $presence.find('item');
  2157. if ($item.length) {
  2158. if ($item.attr('affiliation') == 'owner') {
  2159. this.$el.find('a.configure-chatroom-button').show();
  2160. }
  2161. }
  2162. if ($presence.find("status[code='210']").length) {
  2163. // check if server changed our nick
  2164. this.model.set({'nick': Strophe.getResourceFromJid(from)});
  2165. }
  2166. }
  2167. }
  2168. return true;
  2169. },
  2170. onChatRoomMessage: function (message) {
  2171. var $message = $(message),
  2172. body = $message.children('body').text(),
  2173. jid = $message.attr('from'),
  2174. $chat_content = this.$el.find('.chat-content'),
  2175. resource = Strophe.getResourceFromJid(jid),
  2176. sender = resource && Strophe.unescapeNode(resource) || '',
  2177. delayed = $message.find('delay').length > 0,
  2178. subject = $message.children('subject').text(),
  2179. match, template, dates, message_datetime, message_date, message_date_str;
  2180. if (delayed) {
  2181. message_datetime = moment($message.find('delay').attr('stamp'));
  2182. } else {
  2183. message_datetime = moment();
  2184. }
  2185. // If this message is on a different day than the one received
  2186. // prior, then indicate it on the chatbox.
  2187. dates = $chat_content.find("time").map(function(){return $(this).attr("datetime");}).get();
  2188. message_date = message_datetime.clone().startOf('day');
  2189. message_date_str = message_date.format("YYYY-MM-DD");
  2190. if (_.indexOf(dates, message_date_str) === -1) {
  2191. $chat_content.append(converse.templates.new_day({
  2192. isodate: message_date_str,
  2193. datestring: message_date.format("dddd MMM Do YYYY")
  2194. }));
  2195. }
  2196. this.showStatusMessages($message);
  2197. if (subject) {
  2198. this.$el.find('.chatroom-topic').text(subject).attr('title', subject);
  2199. // # For translators: the %1$s and %2$s parts will get replaced by the user and topic text respectively
  2200. // # Example: Topic set by JC Brand to: Hello World!
  2201. $chat_content.append(
  2202. converse.templates.info({
  2203. 'message': __('Topic set by %1$s to: %2$s', sender, subject)
  2204. }));
  2205. }
  2206. if (!body) { return true; }
  2207. var display_sender = sender === this.model.get('nick') && 'me' || 'room';
  2208. this.showMessage({
  2209. 'message': body,
  2210. 'sender': display_sender,
  2211. 'fullname': sender,
  2212. 'time': message_datetime.format()
  2213. });
  2214. if (display_sender === 'room') {
  2215. // We only emit an event if it's not our own message
  2216. converse.emit('onMessage', message);
  2217. }
  2218. return true;
  2219. },
  2220. onChatRoomRoster: function (roster, room) {
  2221. this.renderChatArea();
  2222. var controlboxview = converse.chatboxviews.get('controlbox'),
  2223. roster_size = _.size(roster),
  2224. $participant_list = this.$el.find('.participant-list'),
  2225. participants = [], keys = _.keys(roster), i;
  2226. this.$el.find('.participant-list').empty();
  2227. for (i=0; i<roster_size; i++) {
  2228. participants.push(
  2229. converse.templates.occupant({
  2230. 'role': roster[keys[i]].role,
  2231. 'nick': Strophe.unescapeNode(keys[i]),
  2232. 'desc_moderator': __('This user is a moderator'),
  2233. 'desc_participant': __('This user can send messages in this room'),
  2234. 'desc_visitor': __('This user can NOT send messages in this room')
  2235. }));
  2236. }
  2237. $participant_list.append(participants.join(""));
  2238. return true;
  2239. }
  2240. });
  2241. this.ChatBoxes = Backbone.Collection.extend({
  2242. model: converse.ChatBox,
  2243. comparator: 'time_opened',
  2244. registerMessageHandler: function () {
  2245. converse.connection.addHandler(
  2246. $.proxy(function (message) {
  2247. this.onMessage(message);
  2248. return true;
  2249. }, this), null, 'message', 'chat');
  2250. },
  2251. onConnected: function () {
  2252. this.localStorage = new Backbone.LocalStorage(
  2253. b64_sha1('converse.chatboxes-'+converse.bare_jid));
  2254. if (!this.get('controlbox')) {
  2255. this.add({
  2256. id: 'controlbox',
  2257. box_id: 'controlbox'
  2258. });
  2259. }
  2260. this.get('controlbox').fetch();
  2261. this.get('controlbox').save();
  2262. // This line below will make sure the Roster is set up
  2263. this.get('controlbox').set({connected:true});
  2264. this.registerMessageHandler();
  2265. // Get cached chatboxes from localstorage
  2266. this.fetch({
  2267. add: true,
  2268. success: $.proxy(function (collection, resp) {
  2269. if (_.include(_.pluck(resp, 'id'), 'controlbox')) {
  2270. // If the controlbox was saved in localstorage, it must be visible
  2271. this.get('controlbox').trigger('show');
  2272. }
  2273. }, this)
  2274. });
  2275. },
  2276. onMessage: function (message) {
  2277. var buddy_jid, $message = $(message),
  2278. message_from = $message.attr('from');
  2279. if (message_from === converse.connection.jid) {
  2280. // FIXME: Forwarded messages should be sent to specific resources,
  2281. // not broadcasted
  2282. return true;
  2283. }
  2284. var $forwarded = $message.children('forwarded');
  2285. var $received = $message.children('received');
  2286. if ($forwarded.length) {
  2287. $message = $forwarded.children('message');
  2288. } else if ($received.length && $received.attr('xmlns') === 'urn:xmpp:carbons:2') {
  2289. $message = $message.children('received').children('forwarded').children('message');
  2290. message_from = $message.attr('from');
  2291. }
  2292. var from = Strophe.getBareJidFromJid(message_from),
  2293. to = Strophe.getBareJidFromJid($message.attr('to')),
  2294. resource, chatbox, roster_item;
  2295. if (from == converse.bare_jid) {
  2296. // I am the sender, so this must be a forwarded message...
  2297. buddy_jid = to;
  2298. resource = Strophe.getResourceFromJid($message.attr('to'));
  2299. } else {
  2300. buddy_jid = from;
  2301. resource = Strophe.getResourceFromJid(message_from);
  2302. }
  2303. chatbox = this.get(buddy_jid);
  2304. roster_item = converse.roster.get(buddy_jid);
  2305. if (roster_item === undefined) {
  2306. // The buddy was likely removed
  2307. converse.log('Could not get roster item for JID '+buddy_jid, 'error');
  2308. return true;
  2309. }
  2310. if (!chatbox) {
  2311. var fullname = roster_item.get('fullname');
  2312. fullname = _.isEmpty(fullname)? buddy_jid: fullname;
  2313. chatbox = this.create({
  2314. 'id': buddy_jid,
  2315. 'jid': buddy_jid,
  2316. 'fullname': fullname,
  2317. 'image_type': roster_item.get('image_type'),
  2318. 'image': roster_item.get('image'),
  2319. 'url': roster_item.get('url')
  2320. });
  2321. }
  2322. chatbox.receiveMessage($message);
  2323. converse.roster.addResource(buddy_jid, resource);
  2324. converse.emit('onMessage', message);
  2325. return true;
  2326. }
  2327. });
  2328. this.ChatBoxViews = Backbone.Overview.extend({
  2329. initialize: function () {
  2330. this.model.on("add", this.onChatAdded, this);
  2331. this.model.on("change:minimized", function (item) {
  2332. if (item.get('minimized') === false) {
  2333. this.trimChats(this.get(item.get('id')));
  2334. } else {
  2335. this.trimChats();
  2336. }
  2337. }, this);
  2338. },
  2339. _ensureElement: function() {
  2340. /* Override method from backbone.js
  2341. * If the #conversejs element doesn't exist, create it.
  2342. */
  2343. if (!this.el) {
  2344. var $el = $('#conversejs');
  2345. if (!$el.length) {
  2346. $el = $('<div id="conversejs">');
  2347. $('body').append($el);
  2348. }
  2349. $el.html(converse.templates.chats_panel());
  2350. this.setElement($el, false);
  2351. } else {
  2352. this.setElement(_.result(this, 'el'), false);
  2353. }
  2354. },
  2355. onChatAdded: function (item) {
  2356. var view = this.get(item.get('id'));
  2357. if (!view) {
  2358. if (item.get('chatroom')) {
  2359. view = new converse.ChatRoomView({'model': item});
  2360. } else if (item.get('box_id') === 'controlbox') {
  2361. view = new converse.ControlBoxView({model: item}).render();
  2362. } else {
  2363. view = new converse.ChatBoxView({model: item});
  2364. }
  2365. this.add(item.get('id'), view);
  2366. } else {
  2367. delete view.model; // Remove ref to old model to help garbage collection
  2368. view.model = item;
  2369. view.initialize();
  2370. }
  2371. this.trimChats(view);
  2372. },
  2373. trimChats: function (newchat) {
  2374. /* This method is called when a newly created chat box will
  2375. * be shown.
  2376. *
  2377. * It checks whether there is enough space on the page to show
  2378. * another chat box. Otherwise it minimize the oldest chat box
  2379. * to create space.
  2380. */
  2381. if (converse.no_trimming || (this.model.length <= 1)) {
  2382. return;
  2383. }
  2384. var oldest_chat,
  2385. controlbox_width = 0,
  2386. $minimized = converse.minimized_chats.$el,
  2387. minimized_width = _.contains(this.model.pluck('minimized'), true) ? $minimized.outerWidth(true) : 0,
  2388. boxes_width = newchat ? newchat.$el.outerWidth(true) : 0,
  2389. new_id = newchat ? newchat.model.get('id') : null,
  2390. controlbox = this.get('controlbox');
  2391. if (!controlbox || !controlbox.$el.is(':visible')) {
  2392. controlbox_width = converse.controlboxtoggle.$el.outerWidth(true);
  2393. } else {
  2394. controlbox_width = controlbox.$el.outerWidth(true);
  2395. }
  2396. _.each(this.getAll(), function (view) {
  2397. var id = view.model.get('id');
  2398. if ((id !== 'controlbox') && (id !== new_id) && (!view.model.get('minimized'))) {
  2399. boxes_width += view.$el.outerWidth(true);
  2400. }
  2401. });
  2402. if ((minimized_width + boxes_width + controlbox_width) > this.$el.outerWidth(true)) {
  2403. oldest_chat = this.getOldestMaximizedChat();
  2404. if (oldest_chat) {
  2405. oldest_chat.minimize();
  2406. }
  2407. }
  2408. },
  2409. getOldestMaximizedChat: function () {
  2410. // Get oldest view (which is not controlbox)
  2411. var i = 0;
  2412. var model = this.model.sort().at(i);
  2413. while (model.get('id') === 'controlbox' || model.get('minimized') === true) {
  2414. i++;
  2415. model = this.model.at(i);
  2416. if (!model) {
  2417. return null;
  2418. }
  2419. }
  2420. return model;
  2421. },
  2422. showChat: function (attrs) {
  2423. var chatbox = this.model.get(attrs.jid);
  2424. if (chatbox) {
  2425. if (chatbox.get('minimized')) {
  2426. chatbox.maximize();
  2427. } else {
  2428. chatbox.trigger('show');
  2429. }
  2430. } else {
  2431. chatbox = this.model.create(attrs, {
  2432. 'error': function (model, response) {
  2433. converse.log(response.responseText);
  2434. }
  2435. });
  2436. }
  2437. return chatbox;
  2438. }
  2439. });
  2440. this.MinimizedChatBoxView = Backbone.View.extend({
  2441. tagName: 'div',
  2442. className: 'chat-head',
  2443. events: {
  2444. 'click .close-chatbox-button': 'close',
  2445. 'click .restore-chat': 'restore'
  2446. },
  2447. initialize: function () {
  2448. this.model.messages.on('add', function (msg) {
  2449. this.updateUnreadMessagesCounter(_.clone(msg.attributes));
  2450. }, this);
  2451. this.model.on('showSentOTRMessage', this.updateUnreadMessagesCounter, this);
  2452. this.model.on('showReceivedOTRMessage', this.updateUnreadMessagesCounter, this);
  2453. this.model.on('change:minimized', this.clearUnreadMessagesCounter, this);
  2454. },
  2455. render: function () {
  2456. var data = _.extend(
  2457. this.model.toJSON(),
  2458. { 'tooltip': __('Click to restore this chat') }
  2459. );
  2460. if (this.model.get('chatroom')) {
  2461. data.title = this.model.get('name');
  2462. this.$el.addClass('chat-head-chatroom');
  2463. } else {
  2464. data.title = this.model.get('fullname');
  2465. this.$el.addClass('chat-head-chatbox');
  2466. }
  2467. return this.$el.html(converse.templates.trimmed_chat(data));
  2468. },
  2469. clearUnreadMessagesCounter: function () {
  2470. if (!this.model.get('minimized')) {
  2471. this.$el.find('.chat-head-message-count').html(0).data('count', 0).hide();
  2472. }
  2473. },
  2474. updateUnreadMessagesCounter: function (msg_dict) {
  2475. var count, $count;
  2476. var msg_time = (typeof msg_dict === 'object' && moment(msg_dict.time)) || moment;
  2477. if (this.model.get('minimized') && (!msg_time.isBefore(this.model.get('time_minimized')))) {
  2478. $count = this.$el.find('.chat-head-message-count');
  2479. count = parseInt($count.data('count') || 0, 10) + 1;
  2480. $count.html(count).data('count', count);
  2481. if (!$count.is(':visible')) { $count.show('fast'); }
  2482. }
  2483. return this;
  2484. },
  2485. close: function (ev) {
  2486. if (ev && ev.preventDefault) {
  2487. ev.preventDefault();
  2488. }
  2489. this.remove();
  2490. this.model.destroy();
  2491. converse.emit('onChatBoxClosed', this);
  2492. return this;
  2493. },
  2494. restore: _.debounce(function (ev) {
  2495. if (ev && ev.preventDefault) {
  2496. ev.preventDefault();
  2497. }
  2498. this.remove();
  2499. this.model.maximize();
  2500. }, 200)
  2501. });
  2502. this.MinimizedChats = Backbone.Overview.extend({
  2503. el: "#minimized-chats",
  2504. events: {
  2505. "click #toggle-minimized-chats": "toggle"
  2506. },
  2507. initialize: function () {
  2508. this.initToggle();
  2509. this.model.on("add", function (item) {
  2510. if (item.get('minimized')) {
  2511. this.addChat(item);
  2512. }
  2513. }, this);
  2514. this.model.on("destroy", this.removeChat, this);
  2515. this.model.on("change:minimized", this.onChanged, this);
  2516. },
  2517. initToggle: function () {
  2518. this.toggleview = new converse.MinimizedChatsToggleView({
  2519. model: new converse.MinimizedChatsToggle()
  2520. });
  2521. var id = b64_sha1('converse.minchatstoggle'+this.bare_jid);
  2522. this.toggleview.model.id = id; // Appears to be necessary for backbone.localStorage
  2523. this.toggleview.model.localStorage = new Backbone.LocalStorage(id);
  2524. this.toggleview.model.fetch();
  2525. },
  2526. render: function () {
  2527. if (this.keys().length === 0) {
  2528. this.$el.hide('fast');
  2529. } else if (this.keys().length === 1) {
  2530. this.$el.show('fast');
  2531. }
  2532. return this.$el;
  2533. },
  2534. toggle: function (ev) {
  2535. if (ev && ev.preventDefault) {
  2536. ev.preventDefault();
  2537. }
  2538. this.toggleview.model.save({'collapsed': !this.toggleview.model.get('collapsed')})
  2539. this.$('.minimized-chats-flyout').toggle();
  2540. },
  2541. onChanged: function (item) {
  2542. if (item.get('minimized')) {
  2543. this.addChat(item);
  2544. } else {
  2545. this.removeChat(item);
  2546. }
  2547. },
  2548. addChat: function (item) {
  2549. var existing = this.get(item.get('id'));
  2550. if (existing && existing.$el.parent().length !== 0) {
  2551. return;
  2552. }
  2553. var view = new converse.MinimizedChatBoxView({model: item});
  2554. this.$('.minimized-chats-flyout').append(view.render());
  2555. this.add(item.get('id'), view);
  2556. this.toggleview.model.set({'num_minimized': this.keys().length});
  2557. this.render();
  2558. },
  2559. removeChat: function (item) {
  2560. this.remove(item.get('id'));
  2561. this.toggleview.model.set({'num_minimized': this.keys().length});
  2562. this.render();
  2563. }
  2564. });
  2565. this.MinimizedChatsToggle = Backbone.Model.extend({
  2566. initialize: function () {
  2567. this.set({
  2568. 'collapsed': this.get('collapsed') || false,
  2569. 'num_minimized': 0
  2570. });
  2571. }
  2572. });
  2573. this.MinimizedChatsToggleView = Backbone.View.extend({
  2574. el: '#toggle-minimized-chats',
  2575. initialize: function () {
  2576. this.model.on('change:num_minimized', this.render, this);
  2577. this.$flyout = this.$el.siblings('.minimized-chats-flyout');
  2578. },
  2579. render: function () {
  2580. this.$el.html(converse.templates.toggle_chats(
  2581. _.extend(this.model.toJSON(), {'Minimized': __('Minimized')})
  2582. ));
  2583. if (this.model.get('collapsed')) {
  2584. this.$flyout.hide();
  2585. } else {
  2586. this.$flyout.show();
  2587. }
  2588. return this.$el;
  2589. },
  2590. });
  2591. this.RosterItem = Backbone.Model.extend({
  2592. initialize: function (attributes, options) {
  2593. var jid = attributes.jid;
  2594. if (!attributes.fullname) {
  2595. attributes.fullname = jid;
  2596. }
  2597. var attrs = _.extend({
  2598. 'id': jid,
  2599. 'user_id': Strophe.getNodeFromJid(jid),
  2600. 'resources': [],
  2601. 'status': ''
  2602. }, attributes);
  2603. attrs.sorted = false;
  2604. attrs.chat_status = 'offline';
  2605. this.set(attrs);
  2606. }
  2607. });
  2608. this.RosterItemView = Backbone.View.extend({
  2609. tagName: 'dd',
  2610. events: {
  2611. "click .accept-xmpp-request": "acceptRequest",
  2612. "click .decline-xmpp-request": "declineRequest",
  2613. "click .open-chat": "openChat",
  2614. "click .remove-xmpp-contact": "removeContact"
  2615. },
  2616. openChat: function (ev) {
  2617. ev.preventDefault();
  2618. return converse.chatboxviews.showChat({
  2619. 'id': this.model.get('jid'),
  2620. 'jid': this.model.get('jid'),
  2621. 'fullname': this.model.get('fullname'),
  2622. 'image_type': this.model.get('image_type'),
  2623. 'image': this.model.get('image'),
  2624. 'url': this.model.get('url'),
  2625. 'status': this.model.get('status')
  2626. });
  2627. },
  2628. removeContact: function (ev) {
  2629. ev.preventDefault();
  2630. var result = confirm(__("Are you sure you want to remove this contact?"));
  2631. if (result === true) {
  2632. var bare_jid = this.model.get('jid');
  2633. converse.connection.roster.remove(bare_jid, function (iq) {
  2634. converse.connection.roster.unauthorize(bare_jid);
  2635. converse.rosterview.model.remove(bare_jid);
  2636. });
  2637. }
  2638. },
  2639. acceptRequest: function (ev) {
  2640. var jid = this.model.get('jid');
  2641. converse.connection.roster.authorize(jid);
  2642. converse.connection.roster.add(jid, this.model.get('fullname'), [], function (iq) {
  2643. converse.connection.roster.subscribe(jid, null, converse.xmppstatus.get('fullname'));
  2644. });
  2645. ev.preventDefault();
  2646. },
  2647. declineRequest: function (ev) {
  2648. ev.preventDefault();
  2649. converse.connection.roster.unauthorize(this.model.get('jid'));
  2650. this.model.destroy();
  2651. },
  2652. render: function () {
  2653. var item = this.model,
  2654. ask = item.get('ask'),
  2655. requesting = item.get('requesting'),
  2656. subscription = item.get('subscription');
  2657. var classes_to_remove = [
  2658. 'current-xmpp-contact',
  2659. 'pending-xmpp-contact',
  2660. 'requesting-xmpp-contact'
  2661. ].concat(_.keys(STATUSES));
  2662. _.each(classes_to_remove,
  2663. function (cls) {
  2664. if (this.el.className.indexOf(cls) !== -1) {
  2665. this.$el.removeClass(cls);
  2666. }
  2667. }, this);
  2668. this.$el.addClass(item.get('chat_status'));
  2669. if (ask === 'subscribe') {
  2670. this.$el.addClass('pending-xmpp-contact');
  2671. this.$el.html(converse.templates.pending_contact(
  2672. _.extend(item.toJSON(), {
  2673. 'desc_remove': __('Click to remove this contact')
  2674. })
  2675. ));
  2676. } else if (requesting === true) {
  2677. this.$el.addClass('requesting-xmpp-contact');
  2678. this.$el.html(converse.templates.requesting_contact(
  2679. _.extend(item.toJSON(), {
  2680. 'label_accept': __('Accept'),
  2681. 'label_decline': __('Decline')
  2682. })
  2683. ));
  2684. converse.controlboxtoggle.showControlBox();
  2685. } else if (subscription === 'both' || subscription === 'to') {
  2686. this.$el.addClass('current-xmpp-contact');
  2687. this.$el.html(converse.templates.roster_item(
  2688. _.extend(item.toJSON(), {
  2689. 'desc_status': STATUSES[item.get('chat_status')||'offline'],
  2690. 'desc_chat': __('Click to chat with this contact'),
  2691. 'desc_remove': __('Click to remove this contact')
  2692. })
  2693. ));
  2694. }
  2695. return this;
  2696. }
  2697. });
  2698. this.RosterItems = Backbone.Collection.extend({
  2699. model: converse.RosterItem,
  2700. comparator : function (rosteritem) {
  2701. var chat_status = rosteritem.get('chat_status'),
  2702. rank = 4;
  2703. switch(chat_status) {
  2704. case 'offline':
  2705. rank = 0;
  2706. break;
  2707. case 'unavailable':
  2708. rank = 1;
  2709. break;
  2710. case 'xa':
  2711. rank = 2;
  2712. break;
  2713. case 'away':
  2714. rank = 3;
  2715. break;
  2716. case 'dnd':
  2717. rank = 4;
  2718. break;
  2719. case 'online':
  2720. rank = 5;
  2721. break;
  2722. }
  2723. return rank;
  2724. },
  2725. subscribeToSuggestedItems: function (msg) {
  2726. $(msg).find('item').each(function () {
  2727. var $this = $(this),
  2728. jid = $this.attr('jid'),
  2729. action = $this.attr('action'),
  2730. fullname = $this.attr('name');
  2731. if (action === 'add') {
  2732. converse.connection.roster.add(jid, fullname, [], function (iq) {
  2733. converse.connection.roster.subscribe(jid, null, converse.xmppstatus.get('fullname'));
  2734. });
  2735. }
  2736. });
  2737. return true;
  2738. },
  2739. isSelf: function (jid) {
  2740. return (Strophe.getBareJidFromJid(jid) === Strophe.getBareJidFromJid(converse.connection.jid));
  2741. },
  2742. addResource: function (bare_jid, resource) {
  2743. var item = this.get(bare_jid),
  2744. resources;
  2745. if (item) {
  2746. resources = item.get('resources');
  2747. if (resources) {
  2748. if (_.indexOf(resources, resource) == -1) {
  2749. resources.push(resource);
  2750. item.set({'resources': resources});
  2751. }
  2752. } else {
  2753. item.set({'resources': [resource]});
  2754. }
  2755. }
  2756. },
  2757. removeResource: function (bare_jid, resource) {
  2758. var item = this.get(bare_jid),
  2759. resources,
  2760. idx;
  2761. if (item) {
  2762. resources = item.get('resources');
  2763. idx = _.indexOf(resources, resource);
  2764. if (idx !== -1) {
  2765. resources.splice(idx, 1);
  2766. item.set({'resources': resources});
  2767. return resources.length;
  2768. }
  2769. }
  2770. return 0;
  2771. },
  2772. subscribeBack: function (jid) {
  2773. var bare_jid = Strophe.getBareJidFromJid(jid);
  2774. if (converse.connection.roster.findItem(bare_jid)) {
  2775. converse.connection.roster.authorize(bare_jid);
  2776. converse.connection.roster.subscribe(jid, null, converse.xmppstatus.get('fullname'));
  2777. } else {
  2778. converse.connection.roster.add(jid, '', [], function (iq) {
  2779. converse.connection.roster.authorize(bare_jid);
  2780. converse.connection.roster.subscribe(jid, null, converse.xmppstatus.get('fullname'));
  2781. });
  2782. }
  2783. },
  2784. unsubscribe: function (jid) {
  2785. /* Upon receiving the presence stanza of type "unsubscribed",
  2786. * the user SHOULD acknowledge receipt of that subscription state
  2787. * notification by sending a presence stanza of type "unsubscribe"
  2788. * this step lets the user's server know that it MUST no longer
  2789. * send notification of the subscription state change to the user.
  2790. */
  2791. converse.xmppstatus.sendPresence('unsubscribe');
  2792. if (converse.connection.roster.findItem(jid)) {
  2793. converse.connection.roster.remove(jid, function (iq) {
  2794. converse.rosterview.model.remove(jid);
  2795. });
  2796. }
  2797. },
  2798. getNumOnlineContacts: function () {
  2799. var count = 0,
  2800. ignored = ['offline', 'unavailable'],
  2801. models = this.models,
  2802. models_length = models.length,
  2803. i;
  2804. if (converse.show_only_online_users) {
  2805. ignored = _.union(ignored, ['dnd', 'xa', 'away']);
  2806. }
  2807. for (i=0; i<models_length; i++) {
  2808. if (_.indexOf(ignored, models[i].get('chat_status')) === -1) {
  2809. count++;
  2810. }
  2811. }
  2812. return count;
  2813. },
  2814. cleanCache: function (items) {
  2815. /* The localstorage cache containing roster contacts might contain
  2816. * some contacts that aren't actually in our roster anymore. We
  2817. * therefore need to remove them now.
  2818. */
  2819. var id, i,
  2820. roster_ids = [];
  2821. for (i=0; i < items.length; ++i) {
  2822. roster_ids.push(items[i].jid);
  2823. }
  2824. for (i=0; i < this.models.length; ++i) {
  2825. id = this.models[i].get('id');
  2826. if (_.indexOf(roster_ids, id) === -1) {
  2827. this.get(id).destroy();
  2828. }
  2829. }
  2830. },
  2831. rosterHandler: function (items) {
  2832. converse.emit('onRoster', items);
  2833. this.cleanCache(items);
  2834. _.each(items, function (item, index, items) {
  2835. if (this.isSelf(item.jid)) { return; }
  2836. var model = this.get(item.jid);
  2837. if (!model) {
  2838. var is_last = (index === (items.length-1)) ? true : false;
  2839. if ((item.subscription === 'none') && (item.ask === null) && !is_last) {
  2840. // We're not interested in zombies
  2841. // (Hack: except if it's the last item, then we still
  2842. // add it so that the roster will be shown).
  2843. return;
  2844. }
  2845. this.create({
  2846. jid: item.jid,
  2847. subscription: item.subscription,
  2848. ask: item.ask,
  2849. fullname: item.name || item.jid,
  2850. is_last: is_last
  2851. });
  2852. } else {
  2853. if ((item.subscription === 'none') && (item.ask === null)) {
  2854. // This user is no longer in our roster
  2855. model.destroy();
  2856. } else if (model.get('subscription') !== item.subscription || model.get('ask') !== item.ask) {
  2857. // only modify model attributes if they are different from the
  2858. // ones that were already set when the rosterItem was added
  2859. model.set({'subscription': item.subscription, 'ask': item.ask, 'requesting': null});
  2860. model.save();
  2861. }
  2862. }
  2863. }, this);
  2864. if (!converse.initial_presence_sent) {
  2865. /* Once we've sent out our initial presence stanza, we'll
  2866. * start receiving presence stanzas from our contacts.
  2867. * We therefore only want to do this after our roster has
  2868. * been set up (otherwise we can't meaningfully process
  2869. * incoming presence stanzas).
  2870. */
  2871. converse.initial_presence_sent = 1;
  2872. converse.xmppstatus.sendPresence();
  2873. }
  2874. },
  2875. handleIncomingSubscription: function (jid) {
  2876. var bare_jid = Strophe.getBareJidFromJid(jid);
  2877. var item = this.get(bare_jid);
  2878. if (!converse.allow_contact_requests) {
  2879. converse.connection.roster.unauthorize(bare_jid);
  2880. return true;
  2881. }
  2882. if (converse.auto_subscribe) {
  2883. if ((!item) || (item.get('subscription') != 'to')) {
  2884. this.subscribeBack(jid);
  2885. } else {
  2886. converse.connection.roster.authorize(bare_jid);
  2887. }
  2888. } else {
  2889. if ((item) && (item.get('subscription') != 'none')) {
  2890. converse.connection.roster.authorize(bare_jid);
  2891. } else {
  2892. if (!this.get(bare_jid)) {
  2893. converse.getVCard(
  2894. bare_jid,
  2895. $.proxy(function (jid, fullname, img, img_type, url) {
  2896. this.add({
  2897. jid: bare_jid,
  2898. subscription: 'none',
  2899. ask: null,
  2900. requesting: true,
  2901. fullname: fullname,
  2902. image: img,
  2903. image_type: img_type,
  2904. url: url,
  2905. vcard_updated: moment().format(),
  2906. is_last: true
  2907. });
  2908. }, this),
  2909. $.proxy(function (jid, fullname, img, img_type, url) {
  2910. converse.log("Error while retrieving vcard");
  2911. // XXX: Should vcard_updated be set here as well?
  2912. this.add({
  2913. jid: bare_jid,
  2914. subscription: 'none',
  2915. ask: null,
  2916. requesting: true,
  2917. fullname: jid,
  2918. is_last: true
  2919. });
  2920. }, this)
  2921. );
  2922. } else {
  2923. return true;
  2924. }
  2925. }
  2926. }
  2927. return true;
  2928. },
  2929. presenceHandler: function (presence) {
  2930. var $presence = $(presence),
  2931. presence_type = $presence.attr('type');
  2932. if (presence_type === 'error') {
  2933. return true;
  2934. }
  2935. var jid = $presence.attr('from'),
  2936. bare_jid = Strophe.getBareJidFromJid(jid),
  2937. resource = Strophe.getResourceFromJid(jid),
  2938. $show = $presence.find('show'),
  2939. chat_status = $show.text() || 'online',
  2940. status_message = $presence.find('status'),
  2941. item;
  2942. if (this.isSelf(bare_jid)) {
  2943. if ((converse.connection.jid !== jid)&&(presence_type !== 'unavailable')) {
  2944. // Another resource has changed it's status, we'll update ours as well.
  2945. // FIXME: We should ideally differentiate between converse.js using
  2946. // resources and other resources (i.e Pidgin etc.)
  2947. converse.xmppstatus.save({'status': chat_status});
  2948. }
  2949. return true;
  2950. } else if (($presence.find('x').attr('xmlns') || '').indexOf(Strophe.NS.MUC) === 0) {
  2951. return true; // Ignore MUC
  2952. }
  2953. item = this.get(bare_jid);
  2954. if (item && (status_message.text() != item.get('status'))) {
  2955. item.save({'status': status_message.text()});
  2956. }
  2957. if ((presence_type === 'subscribed') || (presence_type === 'unsubscribe')) {
  2958. return true;
  2959. } else if (presence_type === 'subscribe') {
  2960. return this.handleIncomingSubscription(jid);
  2961. } else if (presence_type === 'unsubscribed') {
  2962. this.unsubscribe(bare_jid);
  2963. } else if (presence_type === 'unavailable') {
  2964. if (this.removeResource(bare_jid, resource) === 0) {
  2965. if (item) {
  2966. item.set({'chat_status': 'offline'});
  2967. }
  2968. }
  2969. } else if (item) {
  2970. // presence_type is undefined
  2971. this.addResource(bare_jid, resource);
  2972. item.set({'chat_status': chat_status});
  2973. }
  2974. return true;
  2975. }
  2976. });
  2977. this.RosterView = Backbone.Overview.extend({
  2978. tagName: 'dl',
  2979. id: 'converse-roster',
  2980. initialize: function () {
  2981. this.model.on("add", function (item) {
  2982. this.addRosterItemView(item).render(item);
  2983. if (!item.get('vcard_updated')) {
  2984. // This will update the vcard, which triggers a change
  2985. // request which will rerender the roster item.
  2986. converse.getVCard(item.get('jid'));
  2987. }
  2988. }, this);
  2989. this.model.on('change', function (item) {
  2990. if ((_.size(item.changed) === 1) && _.contains(_.keys(item.changed), 'sorted')) {
  2991. return;
  2992. }
  2993. this.updateChatBox(item).render(item);
  2994. }, this);
  2995. this.model.on("remove", function (item) { this.removeRosterItemView(item); }, this);
  2996. this.model.on("destroy", function (item) { this.removeRosterItemView(item); }, this);
  2997. var roster_markup = converse.templates.contacts({
  2998. 'label_contacts': __('My contacts')
  2999. });
  3000. if (converse.allow_contact_requests) {
  3001. roster_markup =
  3002. converse.templates.requesting_contacts({
  3003. 'label_contact_requests': __('Contact requests')
  3004. }) +
  3005. roster_markup +
  3006. converse.templates.pending_contacts({
  3007. 'label_pending_contacts': __('Pending contacts')
  3008. });
  3009. }
  3010. this.$el.hide().html(roster_markup);
  3011. this.model.fetch({add: true}); // Get the cached roster items from localstorage
  3012. },
  3013. updateChatBox: function (item, changed) {
  3014. var chatbox = converse.chatboxes.get(item.get('jid')),
  3015. changes = {};
  3016. if (!chatbox) {
  3017. return this;
  3018. }
  3019. if (_.has(item.changed, 'chat_status')) {
  3020. changes.chat_status = item.get('chat_status');
  3021. }
  3022. if (_.has(item.changed, 'status')) {
  3023. changes.status = item.get('status');
  3024. }
  3025. chatbox.save(changes);
  3026. return this;
  3027. },
  3028. addRosterItemView: function (item) {
  3029. var view = new converse.RosterItemView({model: item});
  3030. this.add(item.id, view);
  3031. return this;
  3032. },
  3033. removeRosterItemView: function (item) {
  3034. if (this.get(item.id)) {
  3035. this.get(item.id).remove();
  3036. this.render();
  3037. }
  3038. return this;
  3039. },
  3040. renderRosterItem: function (item, view) {
  3041. if ((converse.show_only_online_users) && (item.get('chat_status') !== 'online')) {
  3042. view.$el.remove();
  3043. view.delegateEvents();
  3044. return this;
  3045. }
  3046. if ($.contains(document.documentElement, view.el)) {
  3047. view.render();
  3048. } else {
  3049. this.$el.find('#xmpp-contacts').after(view.render().el);
  3050. }
  3051. },
  3052. render: function (item) {
  3053. var $my_contacts = this.$el.find('#xmpp-contacts'),
  3054. $contact_requests = this.$el.find('#xmpp-contact-requests'),
  3055. $pending_contacts = this.$el.find('#pending-xmpp-contacts'),
  3056. sorted = false,
  3057. $count, changed_presence;
  3058. if (item) {
  3059. var jid = item.id,
  3060. view = this.get(item.id),
  3061. ask = item.get('ask'),
  3062. subscription = item.get('subscription'),
  3063. requesting = item.get('requesting'),
  3064. crit = {order:'asc'};
  3065. if ((ask === 'subscribe') && (subscription == 'none')) {
  3066. $pending_contacts.after(view.render().el);
  3067. $pending_contacts.after($pending_contacts.siblings('dd.pending-xmpp-contact').tsort(crit));
  3068. } else if ((ask === 'subscribe') && (subscription == 'from')) {
  3069. // TODO: We have accepted an incoming subscription
  3070. // request and (automatically) made our own subscription request back.
  3071. // It would be useful to update the roster here to show
  3072. // things are happening... (see docs/DEVELOPER.rst)
  3073. $pending_contacts.after(view.render().el);
  3074. $pending_contacts.after($pending_contacts.siblings('dd.pending-xmpp-contact').tsort(crit));
  3075. } else if (requesting === true) {
  3076. $contact_requests.after(view.render().el);
  3077. $contact_requests.after($contact_requests.siblings('dd.requesting-xmpp-contact').tsort(crit));
  3078. } else if (subscription === 'both' || subscription === 'to') {
  3079. this.renderRosterItem(item, view);
  3080. }
  3081. changed_presence = item.changed.chat_status;
  3082. if (changed_presence) {
  3083. this.sortRoster(changed_presence);
  3084. sorted = true;
  3085. }
  3086. if (item.get('is_last')) {
  3087. if (!sorted) {
  3088. this.sortRoster(item.get('chat_status'));
  3089. }
  3090. if (!this.$el.is(':visible')) {
  3091. // Once all initial roster items have been added, we
  3092. // can show the roster.
  3093. this.$el.show();
  3094. }
  3095. }
  3096. }
  3097. // Hide the headings if there are no contacts under them
  3098. _.each([$my_contacts, $contact_requests, $pending_contacts], function (h) {
  3099. if (h.nextUntil('dt').length) {
  3100. if (!h.is(':visible')) {
  3101. h.show();
  3102. }
  3103. }
  3104. else if (h.is(':visible')) {
  3105. h.hide();
  3106. }
  3107. });
  3108. $count = $('#online-count');
  3109. $count.text('('+this.model.getNumOnlineContacts()+')');
  3110. if (!$count.is(':visible')) {
  3111. $count.show();
  3112. }
  3113. converse.emit('onRosterViewUpdated');
  3114. return this;
  3115. },
  3116. sortRoster: function (chat_status) {
  3117. var $my_contacts = this.$el.find('#xmpp-contacts');
  3118. $my_contacts.siblings('dd.current-xmpp-contact.'+chat_status).tsort('a', {order:'asc'});
  3119. $my_contacts.after($my_contacts.siblings('dd.current-xmpp-contact.offline'));
  3120. $my_contacts.after($my_contacts.siblings('dd.current-xmpp-contact.unavailable'));
  3121. $my_contacts.after($my_contacts.siblings('dd.current-xmpp-contact.xa'));
  3122. $my_contacts.after($my_contacts.siblings('dd.current-xmpp-contact.away'));
  3123. $my_contacts.after($my_contacts.siblings('dd.current-xmpp-contact.dnd'));
  3124. $my_contacts.after($my_contacts.siblings('dd.current-xmpp-contact.online'));
  3125. }
  3126. });
  3127. this.XMPPStatus = Backbone.Model.extend({
  3128. initialize: function () {
  3129. this.set({
  3130. 'status' : this.get('status') || 'online'
  3131. });
  3132. this.on('change', $.proxy(function (item) {
  3133. if (this.get('fullname') === undefined) {
  3134. converse.getVCard(
  3135. null, // No 'to' attr when getting one's own vCard
  3136. $.proxy(function (jid, fullname, image, image_type, url) {
  3137. this.save({'fullname': fullname});
  3138. }, this)
  3139. );
  3140. }
  3141. if (_.has(item.changed, 'status')) {
  3142. converse.emit('onStatusChanged', this.get('status'));
  3143. }
  3144. if (_.has(item.changed, 'status_message')) {
  3145. converse.emit('onStatusMessageChanged', this.get('status_message'));
  3146. }
  3147. }, this));
  3148. },
  3149. sendPresence: function (type) {
  3150. if (type === undefined) {
  3151. type = this.get('status') || 'online';
  3152. }
  3153. var status_message = this.get('status_message'),
  3154. presence;
  3155. // Most of these presence types are actually not explicitly sent,
  3156. // but I add all of them here fore reference and future proofing.
  3157. if ((type === 'unavailable') ||
  3158. (type === 'probe') ||
  3159. (type === 'error') ||
  3160. (type === 'unsubscribe') ||
  3161. (type === 'unsubscribed') ||
  3162. (type === 'subscribe') ||
  3163. (type === 'subscribed')) {
  3164. presence = $pres({'type':type});
  3165. } else {
  3166. if (type === 'online') {
  3167. presence = $pres();
  3168. } else {
  3169. presence = $pres().c('show').t(type).up();
  3170. }
  3171. if (status_message) {
  3172. presence.c('status').t(status_message);
  3173. }
  3174. }
  3175. converse.connection.send(presence);
  3176. },
  3177. setStatus: function (value) {
  3178. this.sendPresence(value);
  3179. this.save({'status': value});
  3180. },
  3181. setStatusMessage: function (status_message) {
  3182. converse.connection.send($pres().c('show').t(this.get('status')).up().c('status').t(status_message));
  3183. this.save({'status_message': status_message});
  3184. if (this.xhr_custom_status) {
  3185. $.ajax({
  3186. url: this.xhr_custom_status_url,
  3187. type: 'POST',
  3188. data: {'msg': status_message}
  3189. });
  3190. }
  3191. }
  3192. });
  3193. this.XMPPStatusView = Backbone.View.extend({
  3194. el: "span#xmpp-status-holder",
  3195. events: {
  3196. "click a.choose-xmpp-status": "toggleOptions",
  3197. "click #fancy-xmpp-status-select a.change-xmpp-status-message": "renderStatusChangeForm",
  3198. "submit #set-custom-xmpp-status": "setStatusMessage",
  3199. "click .dropdown dd ul li a": "setStatus"
  3200. },
  3201. toggleOptions: function (ev) {
  3202. ev.preventDefault();
  3203. $(ev.target).parent().parent().siblings('dd').find('ul').toggle('fast');
  3204. },
  3205. renderStatusChangeForm: function (ev) {
  3206. ev.preventDefault();
  3207. var status_message = this.model.get('status') || 'offline';
  3208. var input = converse.templates.change_status_message({
  3209. 'status_message': status_message,
  3210. 'label_custom_status': __('Custom status'),
  3211. 'label_save': __('Save')
  3212. });
  3213. this.$el.find('.xmpp-status').replaceWith(input);
  3214. this.$el.find('.custom-xmpp-status').focus().focus();
  3215. },
  3216. setStatusMessage: function (ev) {
  3217. ev.preventDefault();
  3218. var status_message = $(ev.target).find('input').val();
  3219. if (status_message === "") {
  3220. }
  3221. this.model.setStatusMessage(status_message);
  3222. },
  3223. setStatus: function (ev) {
  3224. ev.preventDefault();
  3225. var $el = $(ev.target),
  3226. value = $el.attr('data-value');
  3227. this.model.setStatus(value);
  3228. this.$el.find(".dropdown dd ul").hide();
  3229. },
  3230. getPrettyStatus: function (stat) {
  3231. var pretty_status;
  3232. if (stat === 'chat') {
  3233. pretty_status = __('online');
  3234. } else if (stat === 'dnd') {
  3235. pretty_status = __('busy');
  3236. } else if (stat === 'xa') {
  3237. pretty_status = __('away for long');
  3238. } else if (stat === 'away') {
  3239. pretty_status = __('away');
  3240. } else {
  3241. pretty_status = __(stat) || __('online');
  3242. }
  3243. return pretty_status;
  3244. },
  3245. updateStatusUI: function (model) {
  3246. if (!(_.has(model.changed, 'status')) && !(_.has(model.changed, 'status_message'))) {
  3247. return;
  3248. }
  3249. var stat = model.get('status');
  3250. // # For translators: the %1$s part gets replaced with the status
  3251. // # Example, I am online
  3252. var status_message = model.get('status_message') || __("I am %1$s", this.getPrettyStatus(stat));
  3253. this.$el.find('#fancy-xmpp-status-select').html(
  3254. converse.templates.chat_status({
  3255. 'chat_status': stat,
  3256. 'status_message': status_message,
  3257. 'desc_custom_status': __('Click here to write a custom status message'),
  3258. 'desc_change_status': __('Click to change your chat status')
  3259. }));
  3260. },
  3261. initialize: function () {
  3262. this.model.on("change", this.updateStatusUI, this);
  3263. },
  3264. render: function () {
  3265. // Replace the default dropdown with something nicer
  3266. var $select = this.$el.find('select#select-xmpp-status'),
  3267. chat_status = this.model.get('status') || 'offline',
  3268. options = $('option', $select),
  3269. $options_target,
  3270. options_list = [],
  3271. that = this;
  3272. this.$el.html(converse.templates.choose_status());
  3273. this.$el.find('#fancy-xmpp-status-select')
  3274. .html(converse.templates.chat_status({
  3275. 'status_message': this.model.get('status_message') || __("I am %1$s", this.getPrettyStatus(chat_status)),
  3276. 'chat_status': chat_status,
  3277. 'desc_custom_status': __('Click here to write a custom status message'),
  3278. 'desc_change_status': __('Click to change your chat status')
  3279. }));
  3280. // iterate through all the <option> elements and add option values
  3281. options.each(function(){
  3282. options_list.push(converse.templates.status_option({
  3283. 'value': $(this).val(),
  3284. 'text': this.text
  3285. }));
  3286. });
  3287. $options_target = this.$el.find("#target dd ul").hide();
  3288. $options_target.append(options_list.join(''));
  3289. $select.remove();
  3290. return this;
  3291. }
  3292. });
  3293. this.Feature = Backbone.Model;
  3294. this.Features = Backbone.Collection.extend({
  3295. /* Service Discovery
  3296. * -----------------
  3297. * This collection stores Feature Models, representing features
  3298. * provided by available XMPP entities (e.g. servers)
  3299. * See XEP-0030 for more details: http://xmpp.org/extensions/xep-0030.html
  3300. * All features are shown here: http://xmpp.org/registrar/disco-features.html
  3301. */
  3302. model: converse.Feature,
  3303. initialize: function () {
  3304. this.localStorage = new Backbone.LocalStorage(
  3305. b64_sha1('converse.features'+converse.bare_jid));
  3306. if (this.localStorage.records.length === 0) {
  3307. // localStorage is empty, so we've likely never queried this
  3308. // domain for features yet
  3309. converse.connection.disco.info(converse.domain, null, $.proxy(this.onInfo, this));
  3310. converse.connection.disco.items(converse.domain, null, $.proxy(this.onItems, this));
  3311. } else {
  3312. this.fetch({add:true});
  3313. }
  3314. },
  3315. onItems: function (stanza) {
  3316. $(stanza).find('query item').each($.proxy(function (idx, item) {
  3317. converse.connection.disco.info(
  3318. $(item).attr('jid'),
  3319. null,
  3320. $.proxy(this.onInfo, this));
  3321. }, this));
  3322. },
  3323. onInfo: function (stanza) {
  3324. var $stanza = $(stanza);
  3325. if (($stanza.find('identity[category=server][type=im]').length === 0) &&
  3326. ($stanza.find('identity[category=conference][type=text]').length === 0)) {
  3327. // This isn't an IM server component
  3328. return;
  3329. }
  3330. $stanza.find('feature').each($.proxy(function (idx, feature) {
  3331. this.create({
  3332. 'var': $(feature).attr('var'),
  3333. 'from': $stanza.attr('from')
  3334. });
  3335. }, this));
  3336. }
  3337. });
  3338. this.LoginPanel = Backbone.View.extend({
  3339. tagName: 'div',
  3340. id: "login-dialog",
  3341. events: {
  3342. 'submit form#converse-login': 'authenticate'
  3343. },
  3344. connect: function ($form, jid, password) {
  3345. if ($form) {
  3346. $form.find('input[type=submit]').hide().after('<span class="spinner login-submit"/>');
  3347. }
  3348. converse.connection = new Strophe.Connection(converse.bosh_service_url);
  3349. converse.connection.connect(jid, password, converse.onConnect);
  3350. },
  3351. showLoginButton: function () {
  3352. var $form = this.$el.find('#converse-login');
  3353. var $button = $form.find('input[type=submit]');
  3354. if ($button.length) {
  3355. $button.show().siblings('span').remove();
  3356. }
  3357. },
  3358. initialize: function (cfg) {
  3359. cfg.$parent.html(this.$el.html(
  3360. converse.templates.login_panel({
  3361. 'label_username': __('XMPP/Jabber Username:'),
  3362. 'label_password': __('Password:'),
  3363. 'label_login': __('Log In')
  3364. })
  3365. ));
  3366. this.$tabs = cfg.$parent.parent().find('#controlbox-tabs');
  3367. },
  3368. render: function () {
  3369. this.$tabs.append(converse.templates.login_tab({label_sign_in: __('Sign in')}));
  3370. this.$el.find('input#jid').focus();
  3371. return this;
  3372. },
  3373. authenticate: function (ev) {
  3374. var $form = $(ev.target),
  3375. $jid_input = $form.find('input[name=jid]'),
  3376. jid = $jid_input.val(),
  3377. $pw_input = $form.find('input[name=password]'),
  3378. password = $pw_input.val(),
  3379. $bsu_input = null,
  3380. errors = false;
  3381. if (! converse.bosh_service_url) {
  3382. $bsu_input = $form.find('input#bosh_service_url');
  3383. converse.bosh_service_url = $bsu_input.val();
  3384. if (! converse.bosh_service_url) {
  3385. errors = true;
  3386. $bsu_input.addClass('error');
  3387. }
  3388. }
  3389. if (! jid) {
  3390. errors = true;
  3391. $jid_input.addClass('error');
  3392. }
  3393. if (! password) {
  3394. errors = true;
  3395. $pw_input.addClass('error');
  3396. }
  3397. if (errors) { return; }
  3398. this.connect($form, jid, password);
  3399. return false;
  3400. },
  3401. remove: function () {
  3402. this.$tabs.empty();
  3403. this.$el.parent().empty();
  3404. }
  3405. });
  3406. this.ControlBoxToggle = Backbone.View.extend({
  3407. tagName: 'a',
  3408. className: 'toggle-controlbox',
  3409. id: 'toggle-controlbox',
  3410. events: {
  3411. 'click': 'onClick'
  3412. },
  3413. attributes: {
  3414. 'href': "#"
  3415. },
  3416. initialize: function () {
  3417. this.render();
  3418. },
  3419. render: function () {
  3420. var toggle = this.$el.html(
  3421. converse.templates.controlbox_toggle({
  3422. 'label_toggle': __('Toggle chat')
  3423. })
  3424. );
  3425. if (converse.show_controlbox_by_default) {
  3426. toggle.hide(); // It's either or
  3427. }
  3428. $('#conversejs').prepend(toggle);
  3429. return this;
  3430. },
  3431. hide: function (callback) {
  3432. this.$el.fadeOut('fast', callback);
  3433. },
  3434. show: function (callback) {
  3435. this.$el.show('fast', callback);
  3436. },
  3437. showControlBox: function () {
  3438. var controlbox = converse.chatboxes.get('controlbox');
  3439. if (!controlbox) {
  3440. converse.chatboxes.add({
  3441. id: 'controlbox',
  3442. box_id: 'controlbox',
  3443. height: converse.default_box_height
  3444. });
  3445. controlbox = converse.chatboxes.get('controlbox');
  3446. if (converse.connection) {
  3447. converse.chatboxes.get('controlbox').save();
  3448. }
  3449. }
  3450. controlbox.trigger('show');
  3451. },
  3452. onClick: function (e) {
  3453. e.preventDefault();
  3454. if ($("div#controlbox").is(':visible')) {
  3455. var controlbox = converse.chatboxes.get('controlbox');
  3456. if (converse.connection) {
  3457. controlbox.destroy();
  3458. } else {
  3459. controlbox.trigger('hide');
  3460. }
  3461. } else {
  3462. this.showControlBox();
  3463. }
  3464. }
  3465. });
  3466. this._initialize = function () {
  3467. this.chatboxes = new this.ChatBoxes();
  3468. this.chatboxviews = new this.ChatBoxViews({model: this.chatboxes});
  3469. this.controlboxtoggle = new this.ControlBoxToggle();
  3470. this.otr = new this.OTR();
  3471. };
  3472. // Initialization
  3473. // --------------
  3474. // This is the end of the initialize method.
  3475. this._initialize();
  3476. if ((this.prebind) && (!this.connection)) {
  3477. if ((!this.jid) || (!this.sid) || (!this.rid) || (!this.bosh_service_url)) {
  3478. this.log('If you set prebind=true, you MUST supply JID, RID and SID values');
  3479. return;
  3480. }
  3481. this.connection = new Strophe.Connection(this.bosh_service_url);
  3482. this.connection.attach(this.jid, this.sid, this.rid, this.onConnect);
  3483. } else if (this.connection) {
  3484. this.onConnected();
  3485. }
  3486. if (this.show_controlbox_by_default) { this.controlboxtoggle.showControlBox(); }
  3487. this.registerGlobalEventHandlers();
  3488. converse.emit('onInitialized');
  3489. };
  3490. return {
  3491. 'initialize': function (settings, callback) {
  3492. converse.initialize(settings, callback);
  3493. },
  3494. 'getRID': function () {
  3495. if (converse.expose_rid_and_sid && typeof converse.connection !== "undefined") {
  3496. return converse.connection._proto.rid;
  3497. }
  3498. return null;
  3499. },
  3500. 'getSID': function () {
  3501. if (converse.expose_rid_and_sid && typeof converse.connection !== "undefined") {
  3502. return converse.connection._proto.sid;
  3503. }
  3504. return null;
  3505. },
  3506. 'once': function(evt, handler) {
  3507. converse.once(evt, handler);
  3508. },
  3509. 'on': function(evt, handler) {
  3510. converse.on(evt, handler);
  3511. },
  3512. 'off': function(evt, handler) {
  3513. converse.off(evt, handler);
  3514. }
  3515. };
  3516. }));