converse.js 204 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665
  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. root.converse = factory(jQuery, _, OTR, DSA, JST, moment);
  25. }
  26. }(this, function ($, _, OTR, DSA, templates, moment) {
  27. // "use strict";
  28. // Cannot use this due to Safari bug.
  29. // See https://github.com/jcbrand/converse.js/issues/196
  30. if (typeof console === "undefined" || typeof console.log === "undefined") {
  31. console = { log: function () {}, error: function () {} };
  32. }
  33. // Configuration of underscore templates (this config is distict to the
  34. // config of requirejs-tpl in main.js). This one is for normal inline
  35. // templates.
  36. // Use Mustache style syntax for variable interpolation
  37. _.templateSettings = {
  38. evaluate : /\{\[([\s\S]+?)\]\}/g,
  39. interpolate : /\{\{([\s\S]+?)\}\}/g
  40. };
  41. // TODO: these non-backbone methods should all be moved to utils.
  42. $.fn.addHyperlinks = function() {
  43. if (this.length > 0) {
  44. this.each(function(i, obj) {
  45. var x = $(obj).html();
  46. var list = x.match(/\b(https?:\/\/|www\.|https?:\/\/www\.)[^\s<]{2,200}\b/g );
  47. if (list) {
  48. for (i=0; i<list.length; i++) {
  49. var prot = list[i].indexOf('http://') === 0 || list[i].indexOf('https://') === 0 ? '' : 'http://';
  50. var escaped_url = encodeURI(decodeURI(list[i])).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
  51. x = x.replace(list[i], "<a target='_blank' href='" + prot + escaped_url + "'>"+ list[i] + "</a>" );
  52. }
  53. }
  54. $(obj).html(x);
  55. });
  56. }
  57. return this;
  58. };
  59. var contains = function (attr, query) {
  60. return function (item) {
  61. if (typeof attr === 'object') {
  62. var value = false;
  63. _.each(attr, function (a) {
  64. value = value || item.get(a).toLowerCase().indexOf(query.toLowerCase()) !== -1;
  65. });
  66. return value;
  67. } else if (typeof attr === 'string') {
  68. return item.get(attr).toLowerCase().indexOf(query.toLowerCase()) !== -1;
  69. } else {
  70. throw new Error('Wrong attribute type. Must be string or array.');
  71. }
  72. };
  73. };
  74. contains.not = function (attr, query) {
  75. return function (item) {
  76. return !(contains(attr, query)(item));
  77. };
  78. };
  79. String.prototype.splitOnce = function (delimiter) {
  80. var components = this.split(delimiter);
  81. return [components.shift(), components.join(delimiter)];
  82. };
  83. var playNotification = function () {
  84. var audio;
  85. if (converse.play_sounds && typeof Audio !== "undefined"){
  86. audio = new Audio("sounds/msg_received.ogg");
  87. if (audio.canPlayType('/audio/ogg')) {
  88. audio.play();
  89. } else {
  90. audio = new Audio("/sounds/msg_received.mp3");
  91. audio.play();
  92. }
  93. }
  94. };
  95. $.fn.addEmoticons = function() {
  96. if (converse.visible_toolbar_buttons.emoticons) {
  97. if (this.length > 0) {
  98. this.each(function(i, obj) {
  99. var text = $(obj).html();
  100. text = text.replace(/&gt;:\)/g, '<span class="emoticon icon-evil"></span>');
  101. text = text.replace(/:\)/g, '<span class="emoticon icon-smiley"></span>');
  102. text = text.replace(/:\-\)/g, '<span class="emoticon icon-smiley"></span>');
  103. text = text.replace(/;\)/g, '<span class="emoticon icon-wink"></span>');
  104. text = text.replace(/;\-\)/g, '<span class="emoticon icon-wink"></span>');
  105. text = text.replace(/:D/g, '<span class="emoticon icon-grin"></span>');
  106. text = text.replace(/:\-D/g, '<span class="emoticon icon-grin"></span>');
  107. text = text.replace(/:P/g, '<span class="emoticon icon-tongue"></span>');
  108. text = text.replace(/:\-P/g, '<span class="emoticon icon-tongue"></span>');
  109. text = text.replace(/:p/g, '<span class="emoticon icon-tongue"></span>');
  110. text = text.replace(/:\-p/g, '<span class="emoticon icon-tongue"></span>');
  111. text = text.replace(/8\)/g, '<span class="emoticon icon-cool"></span>');
  112. text = text.replace(/:S/g, '<span class="emoticon icon-confused"></span>');
  113. text = text.replace(/:\\/g, '<span class="emoticon icon-wondering"></span>');
  114. text = text.replace(/:\/ /g, '<span class="emoticon icon-wondering"></span>');
  115. text = text.replace(/&gt;:\(/g, '<span class="emoticon icon-angry"></span>');
  116. text = text.replace(/:\(/g, '<span class="emoticon icon-sad"></span>');
  117. text = text.replace(/:\-\(/g, '<span class="emoticon icon-sad"></span>');
  118. text = text.replace(/:O/g, '<span class="emoticon icon-shocked"></span>');
  119. text = text.replace(/:\-O/g, '<span class="emoticon icon-shocked"></span>');
  120. text = text.replace(/\=\-O/g, '<span class="emoticon icon-shocked"></span>');
  121. text = text.replace(/\(\^.\^\)b/g, '<span class="emoticon icon-thumbs-up"></span>');
  122. text = text.replace(/&lt;3/g, '<span class="emoticon icon-heart"></span>');
  123. $(obj).html(text);
  124. });
  125. }
  126. }
  127. return this;
  128. };
  129. var converse = {
  130. templates: templates,
  131. emit: function(evt, data) {
  132. $(this).trigger(evt, data);
  133. },
  134. once: function(evt, handler) {
  135. $(this).one(evt, handler);
  136. },
  137. on: function(evt, handler) {
  138. $(this).bind(evt, handler);
  139. },
  140. off: function(evt, handler) {
  141. $(this).unbind(evt, handler);
  142. },
  143. refreshWebkit: function () {
  144. /* This works around a webkit bug. Refresh the browser's viewport,
  145. * otherwise chatboxes are not moved along when one is closed.
  146. */
  147. if ($.browser.webkit) {
  148. var conversejs = document.getElementById('conversejs');
  149. conversejs.style.display = 'none';
  150. conversejs.offsetHeight = conversejs.offsetHeight;
  151. conversejs.style.display = 'block';
  152. }
  153. }
  154. };
  155. converse.initialize = function (settings, callback) {
  156. var converse = this;
  157. // Constants
  158. // ---------
  159. var UNENCRYPTED = 0;
  160. var UNVERIFIED= 1;
  161. var VERIFIED= 2;
  162. var FINISHED = 3;
  163. var KEY = {
  164. ENTER: 13
  165. };
  166. var STATUS_WEIGHTS = {
  167. 'offline': 6,
  168. 'unavailable': 5,
  169. 'xa': 4,
  170. 'away': 3,
  171. 'dnd': 2,
  172. 'online': 1
  173. };
  174. var INACTIVE = 'inactive';
  175. var ACTIVE = 'active';
  176. var COMPOSING = 'composing';
  177. var PAUSED = 'paused';
  178. var GONE = 'gone';
  179. var HAS_CSPRNG = ((typeof crypto !== 'undefined') &&
  180. ((typeof crypto.randomBytes === 'function') ||
  181. (typeof crypto.getRandomValues === 'function')
  182. ));
  183. var HAS_CRYPTO = HAS_CSPRNG && (
  184. (typeof CryptoJS !== "undefined") &&
  185. (typeof OTR !== "undefined") &&
  186. (typeof DSA !== "undefined")
  187. );
  188. var OPENED = 'opened';
  189. var CLOSED = 'closed';
  190. // Default configuration values
  191. // ----------------------------
  192. this.allow_contact_requests = true;
  193. this.allow_dragresize = true;
  194. this.allow_logout = true;
  195. this.allow_muc = true;
  196. this.allow_otr = true;
  197. this.animate = true;
  198. this.auto_list_rooms = false;
  199. this.auto_reconnect = false;
  200. this.auto_subscribe = false;
  201. this.bosh_service_url = undefined; // The BOSH connection manager URL.
  202. this.cache_otr_key = false;
  203. this.debug = false;
  204. this.default_box_height = 324; // The default height, in pixels, for the control box, chat boxes and chatrooms.
  205. this.expose_rid_and_sid = false;
  206. this.forward_messages = false;
  207. this.hide_muc_server = false;
  208. this.i18n = locales.en;
  209. this.keepalive = false;
  210. this.message_carbons = false;
  211. this.no_trimming = false; // Set to true for phantomjs tests (where browser apparently has no width)
  212. this.play_sounds = false;
  213. this.prebind = false;
  214. this.roster_groups = false;
  215. this.show_controlbox_by_default = false;
  216. this.show_only_online_users = false;
  217. this.show_toolbar = true;
  218. this.storage = 'session';
  219. this.use_otr_by_default = false;
  220. this.use_vcards = true;
  221. this.visible_toolbar_buttons = {
  222. 'emoticons': true,
  223. 'call': false,
  224. 'clear': true,
  225. 'toggle_participants': true
  226. };
  227. this.xhr_custom_status = false;
  228. this.xhr_custom_status_url = '';
  229. this.xhr_user_search = false;
  230. this.xhr_user_search_url = '';
  231. // Allow only whitelisted configuration attributes to be overwritten
  232. _.extend(this, _.pick(settings, [
  233. 'allow_contact_requests',
  234. 'allow_dragresize',
  235. 'allow_logout',
  236. 'allow_muc',
  237. 'allow_otr',
  238. 'animate',
  239. 'auto_list_rooms',
  240. 'auto_reconnect',
  241. 'auto_subscribe',
  242. 'bosh_service_url',
  243. 'cache_otr_key',
  244. 'connection',
  245. 'debug',
  246. 'default_box_height',
  247. 'keepalive',
  248. 'message_carbons',
  249. 'expose_rid_and_sid',
  250. 'forward_messages',
  251. 'fullname',
  252. 'hide_muc_server',
  253. 'i18n',
  254. 'jid',
  255. 'no_trimming',
  256. 'play_sounds',
  257. 'prebind',
  258. 'rid',
  259. 'roster_groups',
  260. 'show_controlbox_by_default',
  261. 'show_only_online_users',
  262. 'show_toolbar',
  263. 'sid',
  264. 'storage',
  265. 'use_otr_by_default',
  266. 'use_vcards',
  267. 'xhr_custom_status',
  268. 'xhr_custom_status_url',
  269. 'xhr_user_search',
  270. 'xhr_user_search_url'
  271. ]));
  272. if (settings.visible_toolbar_buttons) {
  273. _.extend(
  274. this.visible_toolbar_buttons,
  275. _.pick(settings.visible_toolbar_buttons, [
  276. 'emoticons', 'call', 'clear', 'toggle_participants'
  277. ]
  278. ));
  279. }
  280. $.fx.off = !this.animate;
  281. // Only allow OTR if we have the capability
  282. this.allow_otr = this.allow_otr && HAS_CRYPTO;
  283. // Only use OTR by default if allow OTR is enabled to begin with
  284. this.use_otr_by_default = this.use_otr_by_default && this.allow_otr;
  285. // Translation machinery
  286. // ---------------------
  287. var __ = $.proxy(function (str) {
  288. // Translation factory
  289. if (this.i18n === undefined) {
  290. this.i18n = locales.en;
  291. }
  292. var t = this.i18n.translate(str);
  293. if (arguments.length>1) {
  294. return t.fetch.apply(t, [].slice.call(arguments,1));
  295. } else {
  296. return t.fetch();
  297. }
  298. }, this);
  299. var ___ = function (str) {
  300. /* XXX: This is part of a hack to get gettext to scan strings to be
  301. * translated. Strings we cannot send to the function above because
  302. * they require variable interpolation and we don't yet have the
  303. * variables at scan time.
  304. *
  305. * See actionInfoMessages
  306. */
  307. return str;
  308. };
  309. // Translation aware constants
  310. // ---------------------------
  311. var OTR_CLASS_MAPPING = {};
  312. OTR_CLASS_MAPPING[UNENCRYPTED] = 'unencrypted';
  313. OTR_CLASS_MAPPING[UNVERIFIED] = 'unverified';
  314. OTR_CLASS_MAPPING[VERIFIED] = 'verified';
  315. OTR_CLASS_MAPPING[FINISHED] = 'finished';
  316. var OTR_TRANSLATED_MAPPING = {};
  317. OTR_TRANSLATED_MAPPING[UNENCRYPTED] = __('unencrypted');
  318. OTR_TRANSLATED_MAPPING[UNVERIFIED] = __('unverified');
  319. OTR_TRANSLATED_MAPPING[VERIFIED] = __('verified');
  320. OTR_TRANSLATED_MAPPING[FINISHED] = __('finished');
  321. var STATUSES = {
  322. 'dnd': __('This contact is busy'),
  323. 'online': __('This contact is online'),
  324. 'offline': __('This contact is offline'),
  325. 'unavailable': __('This contact is unavailable'),
  326. 'xa': __('This contact is away for an extended period'),
  327. 'away': __('This contact is away')
  328. };
  329. var DESC_GROUP_TOGGLE = __('Click to hide these contacts');
  330. var HEADER_CURRENT_CONTACTS = __('My contacts');
  331. var HEADER_PENDING_CONTACTS = __('Pending contacts');
  332. var HEADER_REQUESTING_CONTACTS = __('Contact requests');
  333. var HEADER_UNGROUPED = __('Ungrouped');
  334. var LABEL_CONTACTS = __('Contacts');
  335. var LABEL_GROUPS = __('Groups');
  336. var HEADER_WEIGHTS = {};
  337. HEADER_WEIGHTS[HEADER_CURRENT_CONTACTS] = 0;
  338. HEADER_WEIGHTS[HEADER_UNGROUPED] = 1;
  339. HEADER_WEIGHTS[HEADER_REQUESTING_CONTACTS] = 2;
  340. HEADER_WEIGHTS[HEADER_PENDING_CONTACTS] = 3;
  341. // Module-level variables
  342. // ----------------------
  343. this.callback = callback || function () {};
  344. this.initial_presence_sent = 0;
  345. this.msg_counter = 0;
  346. // Module-level functions
  347. // ----------------------
  348. this.giveFeedback = function (message, klass) {
  349. $('.conn-feedback').attr('class', 'conn-feedback').text(message);
  350. if (klass) {
  351. $('.conn-feedback').addClass(klass);
  352. }
  353. };
  354. this.log = function (txt, level) {
  355. if (this.debug) {
  356. if (level == 'error') {
  357. console.log('ERROR: '+txt);
  358. } else {
  359. console.log(txt);
  360. }
  361. }
  362. };
  363. this.getVCard = function (jid, callback, errback) {
  364. if (!this.use_vcards) {
  365. if (callback) {
  366. callback(jid, jid);
  367. }
  368. return;
  369. }
  370. converse.connection.vcard.get(
  371. $.proxy(function (iq) {
  372. // Successful callback
  373. var $vcard = $(iq).find('vCard');
  374. var fullname = $vcard.find('FN').text(),
  375. img = $vcard.find('BINVAL').text(),
  376. img_type = $vcard.find('TYPE').text(),
  377. url = $vcard.find('URL').text();
  378. if (jid) {
  379. var contact = converse.roster.get(jid);
  380. if (contact) {
  381. fullname = _.isEmpty(fullname)? contact.get('fullname') || jid: fullname;
  382. contact.save({
  383. 'fullname': fullname,
  384. 'image_type': img_type,
  385. 'image': img,
  386. 'url': url,
  387. 'vcard_updated': moment().format()
  388. });
  389. }
  390. }
  391. if (callback) {
  392. callback(jid, fullname, img, img_type, url);
  393. }
  394. }, this),
  395. jid,
  396. function (iq) {
  397. // Error callback
  398. var contact = converse.roster.get(jid);
  399. if (contact) {
  400. contact.save({
  401. 'vcard_updated': moment().format()
  402. });
  403. }
  404. if (errback) {
  405. errback(jid, iq);
  406. }
  407. }
  408. );
  409. };
  410. this.reconnect = function () {
  411. converse.giveFeedback(__('Reconnecting'), 'error');
  412. converse.emit('reconnect');
  413. if (!converse.prebind) {
  414. this.connection.connect(
  415. this.connection.jid,
  416. this.connection.pass,
  417. function (status, condition) {
  418. converse.onConnect(status, condition, true);
  419. },
  420. this.connection.wait,
  421. this.connection.hold,
  422. this.connection.route
  423. );
  424. }
  425. };
  426. this.renderLoginPanel = function () {
  427. converse._tearDown();
  428. var view = converse.chatboxviews.get('controlbox');
  429. view.model.set({connected:false});
  430. view.renderLoginPanel();
  431. };
  432. this.onConnect = function (status, condition, reconnect) {
  433. var $button, $form;
  434. if ((status === Strophe.Status.CONNECTED) ||
  435. (status === Strophe.Status.ATTACHED)) {
  436. if ((typeof reconnect !== 'undefined') && (reconnect)) {
  437. converse.log(status === Strophe.Status.CONNECTED ? 'Reconnected' : 'Reattached');
  438. converse.onReconnected();
  439. } else {
  440. converse.log(status === Strophe.Status.CONNECTED ? 'Connected' : 'Attached');
  441. converse.onConnected();
  442. }
  443. } else if (status === Strophe.Status.DISCONNECTED) {
  444. converse.giveFeedback(__('Disconnected'), 'error');
  445. if (converse.auto_reconnect) {
  446. converse.reconnect();
  447. } else {
  448. converse.renderLoginPanel();
  449. }
  450. } else if (status === Strophe.Status.Error) {
  451. converse.renderLoginPanel();
  452. converse.giveFeedback(__('Error'), 'error');
  453. } else if (status === Strophe.Status.CONNECTING) {
  454. converse.giveFeedback(__('Connecting'));
  455. } else if (status === Strophe.Status.CONNFAIL) {
  456. converse.renderLoginPanel();
  457. converse.giveFeedback(__('Connection Failed'), 'error');
  458. } else if (status === Strophe.Status.AUTHENTICATING) {
  459. converse.giveFeedback(__('Authenticating'));
  460. } else if (status === Strophe.Status.AUTHFAIL) {
  461. converse.renderLoginPanel();
  462. converse.giveFeedback(__('Authentication Failed'), 'error');
  463. } else if (status === Strophe.Status.DISCONNECTING) {
  464. if (!converse.connection.connected) {
  465. converse.renderLoginPanel();
  466. } else {
  467. converse.giveFeedback(__('Disconnecting'), 'error');
  468. }
  469. }
  470. };
  471. this.applyHeightResistance = function (height) {
  472. /* This method applies some resistance/gravity around the
  473. * "default_box_height". If "height" is close enough to
  474. * default_box_height, then that is returned instead.
  475. */
  476. if (typeof height === 'undefined') {
  477. return converse.default_box_height;
  478. }
  479. var resistance = 10;
  480. if ((height !== converse.default_box_height) &&
  481. (Math.abs(height - converse.default_box_height) < resistance)) {
  482. return converse.default_box_height;
  483. }
  484. return height;
  485. };
  486. this.updateMsgCounter = function () {
  487. if (this.msg_counter > 0) {
  488. if (document.title.search(/^Messages \(\d+\) /) == -1) {
  489. document.title = "Messages (" + this.msg_counter + ") " + document.title;
  490. } else {
  491. document.title = document.title.replace(/^Messages \(\d+\) /, "Messages (" + this.msg_counter + ") ");
  492. }
  493. window.blur();
  494. window.focus();
  495. } else if (document.title.search(/^Messages \(\d+\) /) != -1) {
  496. document.title = document.title.replace(/^Messages \(\d+\) /, "");
  497. }
  498. };
  499. this.incrementMsgCounter = function () {
  500. this.msg_counter += 1;
  501. this.updateMsgCounter();
  502. };
  503. this.clearMsgCounter = function () {
  504. this.msg_counter = 0;
  505. this.updateMsgCounter();
  506. };
  507. this.initStatus = function (callback) {
  508. this.xmppstatus = new this.XMPPStatus();
  509. var id = b64_sha1('converse.xmppstatus-'+converse.bare_jid);
  510. this.xmppstatus.id = id; // Appears to be necessary for backbone.browserStorage
  511. this.xmppstatus.browserStorage = new Backbone.BrowserStorage[converse.storage](id);
  512. this.xmppstatus.fetch({success: callback, error: callback});
  513. };
  514. this.initSession = function () {
  515. this.session = new this.BOSHSession();
  516. var id = b64_sha1('converse.bosh-session');
  517. this.session.id = id; // Appears to be necessary for backbone.browserStorage
  518. this.session.browserStorage = new Backbone.BrowserStorage[converse.storage](id);
  519. this.session.fetch();
  520. $(window).on('beforeunload', $.proxy(function () {
  521. if (converse.connection.connected) {
  522. this.setSession();
  523. } else {
  524. this.clearSession();
  525. }
  526. }, this));
  527. };
  528. this.clearSession = function () {
  529. this.session.browserStorage._clear();
  530. // XXX: this should perhaps go into the beforeunload handler
  531. converse.chatboxes.get('controlbox').save({'connected': false});
  532. };
  533. this.setSession = function () {
  534. if (this.keepalive) {
  535. this.session.save({
  536. jid: this.connection.jid,
  537. rid: this.connection._proto.rid,
  538. sid: this.connection._proto.sid
  539. });
  540. }
  541. };
  542. this.logOut = function () {
  543. converse.chatboxviews.closeAllChatBoxes(false);
  544. converse.clearSession();
  545. converse.connection.disconnect();
  546. converse.connection.reset();
  547. };
  548. this.registerGlobalEventHandlers = function () {
  549. $(document).click(function() {
  550. if ($('.toggle-otr ul').is(':visible')) {
  551. $('.toggle-otr ul', this).slideUp();
  552. }
  553. if ($('.toggle-smiley ul').is(':visible')) {
  554. $('.toggle-smiley ul', this).slideUp();
  555. }
  556. });
  557. $(document).on('mousemove', $.proxy(function (ev) {
  558. if (!this.resized_chatbox || !this.allow_dragresize) { return true; }
  559. ev.preventDefault();
  560. this.resized_chatbox.resizeChatBox(ev);
  561. }, this));
  562. $(document).on('mouseup', $.proxy(function (ev) {
  563. if (!this.resized_chatbox || !this.allow_dragresize) { return true; }
  564. ev.preventDefault();
  565. var height = this.applyHeightResistance(this.resized_chatbox.height);
  566. if (this.connection.connected) {
  567. this.resized_chatbox.model.save({'height': height});
  568. } else {
  569. this.resized_chatbox.model.set({'height': height});
  570. }
  571. this.resized_chatbox = null;
  572. }, this));
  573. $(window).on("blur focus", $.proxy(function (ev) {
  574. if ((this.windowState != ev.type) && (ev.type == 'focus')) {
  575. converse.clearMsgCounter();
  576. }
  577. this.windowState = ev.type;
  578. },this));
  579. $(window).on("resize", _.debounce($.proxy(function (ev) {
  580. this.chatboxviews.trimChats();
  581. },this), 200));
  582. };
  583. this.onReconnected = function () {
  584. // We need to re-register all the event handlers on the newly
  585. // created connection.
  586. this.initStatus($.proxy(function () {
  587. this.registerRosterXHandler();
  588. this.registerPresenceHandler();
  589. this.chatboxes.registerMessageHandler();
  590. converse.xmppstatus.sendPresence();
  591. this.giveFeedback(__('Online Contacts'));
  592. }, this));
  593. };
  594. this.enableCarbons = function () {
  595. /* Ask the XMPP server to enable Message Carbons
  596. * See XEP-0280 https://xmpp.org/extensions/xep-0280.html#enabling
  597. */
  598. if (!this.message_carbons) {
  599. return;
  600. }
  601. var carbons_iq = new Strophe.Builder('iq', {
  602. from: this.connection.jid,
  603. id: 'enablecarbons',
  604. type: 'set'
  605. })
  606. .c('enable', {xmlns: 'urn:xmpp:carbons:2'});
  607. this.connection.send(carbons_iq);
  608. this.connection.addHandler(function(iq) {
  609. //TODO: check if carbons was enabled:
  610. }, null, "iq", null, "enablecarbons");
  611. };
  612. this.onConnected = function () {
  613. if (this.debug) {
  614. this.connection.xmlInput = function (body) { console.log(body); };
  615. this.connection.xmlOutput = function (body) { console.log(body); };
  616. Strophe.log = function (level, msg) { console.log(level+' '+msg); };
  617. Strophe.error = function (msg) {
  618. console.log('ERROR: '+msg);
  619. };
  620. }
  621. // When reconnecting, there might be some open chat boxes. We don't
  622. // know whether these boxes are of the same account or not, so we
  623. // close them now.
  624. this.chatboxviews.closeAllChatBoxes();
  625. this.setSession();
  626. this.jid = this.connection.jid;
  627. this.bare_jid = Strophe.getBareJidFromJid(this.connection.jid);
  628. this.domain = Strophe.getDomainFromJid(this.connection.jid);
  629. this.minimized_chats = new converse.MinimizedChats({model: this.chatboxes});
  630. this.features = new this.Features();
  631. this.enableCarbons();
  632. this.initStatus($.proxy(function () {
  633. this.chatboxes.onConnected();
  634. this.giveFeedback(__('Online Contacts'));
  635. if (this.callback) {
  636. if (this.connection.service === 'jasmine tests') {
  637. // XXX: Call back with the internal converse object. This
  638. // object should never be exposed to production systems.
  639. // 'jasmine tests' is an invalid http bind service value,
  640. // so we're sure that this is just for tests.
  641. //
  642. // TODO: We might need to consider websockets, which
  643. // probably won't use the 'service' attr. Current
  644. // strophe.js version used by converse.js doesn't support
  645. // websockets.
  646. this.callback(this);
  647. } else {
  648. this.callback();
  649. }
  650. }
  651. }, this));
  652. converse.emit('ready');
  653. };
  654. // Backbone Models and Views
  655. // -------------------------
  656. this.OTR = Backbone.Model.extend({
  657. // A model for managing OTR settings.
  658. getSessionPassphrase: function () {
  659. if (converse.prebind) {
  660. var key = b64_sha1(converse.connection.jid),
  661. pass = window.sessionStorage[key];
  662. if (typeof pass === 'undefined') {
  663. pass = Math.floor(Math.random()*4294967295).toString();
  664. window.sessionStorage[key] = pass;
  665. }
  666. return pass;
  667. } else {
  668. return converse.connection.pass;
  669. }
  670. },
  671. generatePrivateKey: function () {
  672. var key = new DSA();
  673. var jid = converse.connection.jid;
  674. if (converse.cache_otr_key) {
  675. var cipher = CryptoJS.lib.PasswordBasedCipher;
  676. var pass = this.getSessionPassphrase();
  677. if (typeof pass !== "undefined") {
  678. // Encrypt the key and set in sessionStorage. Also store instance tag.
  679. window.sessionStorage[b64_sha1(jid+'priv_key')] =
  680. cipher.encrypt(CryptoJS.algo.AES, key.packPrivate(), pass).toString();
  681. window.sessionStorage[b64_sha1(jid+'instance_tag')] = instance_tag;
  682. window.sessionStorage[b64_sha1(jid+'pass_check')] =
  683. cipher.encrypt(CryptoJS.algo.AES, 'match', pass).toString();
  684. }
  685. }
  686. return key;
  687. }
  688. });
  689. this.Message = Backbone.Model;
  690. this.Messages = Backbone.Collection.extend({
  691. model: converse.Message
  692. });
  693. this.ChatBox = Backbone.Model.extend({
  694. initialize: function () {
  695. var height = converse.applyHeightResistance(this.get('height'));
  696. if (this.get('box_id') !== 'controlbox') {
  697. this.messages = new converse.Messages();
  698. this.messages.browserStorage = new Backbone.BrowserStorage[converse.storage](
  699. b64_sha1('converse.messages'+this.get('jid')+converse.bare_jid));
  700. this.save({
  701. 'box_id' : b64_sha1(this.get('jid')),
  702. 'height': height,
  703. 'minimized': this.get('minimized') || false,
  704. 'otr_status': this.get('otr_status') || UNENCRYPTED,
  705. 'time_minimized': this.get('time_minimized') || moment(),
  706. 'time_opened': this.get('time_opened') || moment().valueOf(),
  707. 'user_id' : Strophe.getNodeFromJid(this.get('jid')),
  708. 'num_unread': this.get('num_unread') || 0,
  709. 'url': ''
  710. });
  711. } else {
  712. this.set({
  713. 'height': height,
  714. 'time_opened': moment(0).valueOf(),
  715. 'num_unread': this.get('num_unread') || 0
  716. });
  717. }
  718. },
  719. maximize: function () {
  720. this.save({
  721. 'minimized': false,
  722. 'time_opened': moment().valueOf()
  723. });
  724. },
  725. minimize: function () {
  726. this.save({
  727. 'minimized': true,
  728. 'time_minimized': moment().format()
  729. });
  730. },
  731. getSession: function (callback) {
  732. var cipher = CryptoJS.lib.PasswordBasedCipher;
  733. var result, pass, instance_tag, saved_key, pass_check;
  734. if (converse.cache_otr_key) {
  735. pass = converse.otr.getSessionPassphrase();
  736. if (typeof pass !== "undefined") {
  737. instance_tag = window.sessionStorage[b64_sha1(this.id+'instance_tag')];
  738. saved_key = window.sessionStorage[b64_sha1(this.id+'priv_key')];
  739. pass_check = window.sessionStorage[b64_sha1(this.connection.jid+'pass_check')];
  740. if (saved_key && instance_tag && typeof pass_check !== 'undefined') {
  741. var decrypted = cipher.decrypt(CryptoJS.algo.AES, saved_key, pass);
  742. var key = DSA.parsePrivate(decrypted.toString(CryptoJS.enc.Latin1));
  743. if (cipher.decrypt(CryptoJS.algo.AES, pass_check, pass).toString(CryptoJS.enc.Latin1) === 'match') {
  744. // Verified that the passphrase is still the same
  745. this.trigger('showHelpMessages', [__('Re-establishing encrypted session')]);
  746. callback({
  747. 'key': key,
  748. 'instance_tag': instance_tag
  749. });
  750. return; // Our work is done here
  751. }
  752. }
  753. }
  754. }
  755. // We need to generate a new key and instance tag
  756. this.trigger('showHelpMessages', [
  757. __('Generating private key.'),
  758. __('Your browser might become unresponsive.')],
  759. null,
  760. true // show spinner
  761. );
  762. setTimeout(function () {
  763. callback({
  764. 'key': converse.otr.generatePrivateKey.apply(this),
  765. 'instance_tag': OTR.makeInstanceTag()
  766. });
  767. }, 500);
  768. },
  769. updateOTRStatus: function (state) {
  770. switch (state) {
  771. case OTR.CONST.STATUS_AKE_SUCCESS:
  772. if (this.otr.msgstate === OTR.CONST.MSGSTATE_ENCRYPTED) {
  773. this.save({'otr_status': UNVERIFIED});
  774. }
  775. break;
  776. case OTR.CONST.STATUS_END_OTR:
  777. if (this.otr.msgstate === OTR.CONST.MSGSTATE_FINISHED) {
  778. this.save({'otr_status': FINISHED});
  779. } else if (this.otr.msgstate === OTR.CONST.MSGSTATE_PLAINTEXT) {
  780. this.save({'otr_status': UNENCRYPTED});
  781. }
  782. break;
  783. }
  784. },
  785. onSMP: function (type, data) {
  786. // Event handler for SMP (Socialist's Millionaire Protocol)
  787. // used by OTR (off-the-record).
  788. switch (type) {
  789. case 'question':
  790. this.otr.smpSecret(prompt(__(
  791. 'Authentication request from %1$s\n\nYour buddy is attempting to verify your identity, by asking you the question below.\n\n%2$s',
  792. [this.get('fullname'), data])));
  793. break;
  794. case 'trust':
  795. if (data === true) {
  796. this.save({'otr_status': VERIFIED});
  797. } else {
  798. this.trigger(
  799. 'showHelpMessages',
  800. [__("Could not verify this user's identify.")],
  801. 'error');
  802. this.save({'otr_status': UNVERIFIED});
  803. }
  804. break;
  805. default:
  806. throw new Error('Unknown type.');
  807. }
  808. },
  809. initiateOTR: function (query_msg) {
  810. // Sets up an OTR object through which we can send and receive
  811. // encrypted messages.
  812. //
  813. // If 'query_msg' is passed in, it means there is an alread incoming
  814. // query message from our buddy. Otherwise, it is us who will
  815. // send the query message to them.
  816. this.save({'otr_status': UNENCRYPTED});
  817. var session = this.getSession($.proxy(function (session) {
  818. this.otr = new OTR({
  819. fragment_size: 140,
  820. send_interval: 200,
  821. priv: session.key,
  822. instance_tag: session.instance_tag,
  823. debug: this.debug
  824. });
  825. this.otr.on('status', $.proxy(this.updateOTRStatus, this));
  826. this.otr.on('smp', $.proxy(this.onSMP, this));
  827. this.otr.on('ui', $.proxy(function (msg) {
  828. this.trigger('showReceivedOTRMessage', msg);
  829. }, this));
  830. this.otr.on('io', $.proxy(function (msg) {
  831. this.trigger('sendMessageStanza', msg);
  832. }, this));
  833. this.otr.on('error', $.proxy(function (msg) {
  834. this.trigger('showOTRError', msg);
  835. }, this));
  836. this.trigger('showHelpMessages', [__('Exchanging private key with buddy.')]);
  837. if (query_msg) {
  838. this.otr.receiveMsg(query_msg);
  839. } else {
  840. this.otr.sendQueryMsg();
  841. }
  842. }, this));
  843. },
  844. endOTR: function () {
  845. if (this.otr) {
  846. this.otr.endOtr();
  847. }
  848. this.save({'otr_status': UNENCRYPTED});
  849. },
  850. createMessage: function ($message) {
  851. var body = $message.children('body').text(),
  852. composing = $message.find('composing'),
  853. paused = $message.find('paused'),
  854. delayed = $message.find('delay').length > 0,
  855. fullname = this.get('fullname'),
  856. is_groupchat = $message.attr('type') === 'groupchat',
  857. stamp, time, sender, from;
  858. if (is_groupchat) {
  859. from = Strophe.unescapeNode(Strophe.getResourceFromJid($message.attr('from')));
  860. } else {
  861. from = Strophe.getBareJidFromJid($message.attr('from'));
  862. }
  863. fullname = (_.isEmpty(fullname)? from: fullname).split(' ')[0];
  864. if (!body) {
  865. if (composing.length || paused.length) {
  866. this.messages.add({
  867. fullname: fullname,
  868. sender: 'them',
  869. delayed: delayed,
  870. time: moment().format(),
  871. composing: composing.length,
  872. paused: paused.length
  873. });
  874. }
  875. } else {
  876. if (delayed) {
  877. stamp = $message.find('delay').attr('stamp');
  878. time = stamp;
  879. } else {
  880. time = moment().format();
  881. }
  882. if ((is_groupchat && from === this.get('nick')) || (!is_groupchat && from == converse.bare_jid)) {
  883. sender = 'me';
  884. } else {
  885. sender = 'them';
  886. }
  887. this.messages.create({
  888. fullname: fullname,
  889. sender: sender,
  890. delayed: delayed,
  891. time: time,
  892. message: body
  893. });
  894. }
  895. },
  896. receiveMessage: function ($message) {
  897. var $body = $message.children('body');
  898. var text = ($body.length > 0 ? $body.text() : undefined);
  899. if ((!text) || (!converse.allow_otr)) {
  900. return this.createMessage($message);
  901. }
  902. if (text.match(/^\?OTRv23?/)) {
  903. this.initiateOTR(text);
  904. } else {
  905. if (_.contains([UNVERIFIED, VERIFIED], this.get('otr_status'))) {
  906. this.otr.receiveMsg(text);
  907. } else {
  908. if (text.match(/^\?OTR/)) {
  909. if (!this.otr) {
  910. this.initiateOTR(text);
  911. } else {
  912. this.otr.receiveMsg(text);
  913. }
  914. } else {
  915. // Normal unencrypted message.
  916. this.createMessage($message);
  917. }
  918. }
  919. }
  920. }
  921. });
  922. this.ChatBoxView = Backbone.View.extend({
  923. length: 200,
  924. tagName: 'div',
  925. className: 'chatbox',
  926. is_chatroom: false, // This is not a multi-user chatroom
  927. events: {
  928. 'click .close-chatbox-button': 'close',
  929. 'click .toggle-chatbox-button': 'minimize',
  930. 'keypress textarea.chat-textarea': 'keyPressed',
  931. 'click .toggle-smiley': 'toggleEmoticonMenu',
  932. 'click .toggle-smiley ul li': 'insertEmoticon',
  933. 'click .toggle-clear': 'clearMessages',
  934. 'click .toggle-otr': 'toggleOTRMenu',
  935. 'click .start-otr': 'startOTRFromToolbar',
  936. 'click .end-otr': 'endOTR',
  937. 'click .auth-otr': 'authOTR',
  938. 'click .toggle-call': 'toggleCall',
  939. 'mousedown .dragresize-tm': 'onDragResizeStart'
  940. },
  941. initialize: function (){
  942. this.model.messages.on('add', this.onMessageAdded, this);
  943. this.model.on('show', this.show, this);
  944. this.model.on('destroy', this.hide, this);
  945. this.model.on('change', this.onChange, this);
  946. this.model.on('showOTRError', this.showOTRError, this);
  947. this.model.on('buddyStartsOTR', this.buddyStartsOTR, this);
  948. this.model.on('showHelpMessages', this.showHelpMessages, this);
  949. this.model.on('sendMessageStanza', this.sendMessageStanza, this);
  950. this.model.on('showSentOTRMessage', function (text) {
  951. this.showMessage({'message': text, 'sender': 'me'});
  952. }, this);
  953. this.model.on('showReceivedOTRMessage', function (text) {
  954. this.showMessage({'message': text, 'sender': 'them'});
  955. }, this);
  956. this.updateVCard();
  957. this.$el.insertAfter(converse.chatboxviews.get("controlbox").$el);
  958. this.render().model.messages.fetch({add: true});
  959. if (this.model.get('minimized')) {
  960. this.hide();
  961. } else {
  962. this.show();
  963. }
  964. if ((_.contains([UNVERIFIED, VERIFIED], this.model.get('otr_status'))) || converse.use_otr_by_default) {
  965. this.model.initiateOTR();
  966. }
  967. },
  968. render: function () {
  969. this.$el.attr('id', this.model.get('box_id'))
  970. .html(converse.templates.chatbox(
  971. _.extend(this.model.toJSON(), {
  972. show_toolbar: converse.show_toolbar,
  973. label_personal_message: __('Personal message')
  974. }
  975. )
  976. )
  977. );
  978. this.renderToolbar().renderAvatar();
  979. converse.emit('chatBoxOpened', this);
  980. setTimeout(function () {
  981. converse.refreshWebkit();
  982. }, 50);
  983. return this.showStatusMessage();
  984. },
  985. initDragResize: function () {
  986. this.prev_pageY = 0; // To store last known mouse position
  987. if (converse.connection.connected) {
  988. this.height = this.model.get('height');
  989. }
  990. return this;
  991. },
  992. showStatusNotification: function (message, keep_old) {
  993. var $chat_content = this.$el.find('.chat-content');
  994. if (!keep_old) {
  995. $chat_content.find('div.chat-event').remove();
  996. }
  997. $chat_content.append($('<div class="chat-event"></div>').text(message));
  998. this.scrollDown();
  999. },
  1000. clearChatRoomMessages: function (ev) {
  1001. ev.stopPropagation();
  1002. var result = confirm(__("Are you sure you want to clear the messages from this room?"));
  1003. if (result === true) {
  1004. this.$el.find('.chat-content').empty();
  1005. }
  1006. return this;
  1007. },
  1008. showMessage: function (msg_dict) {
  1009. var $content = this.$el.find('.chat-content'),
  1010. msg_time = moment(msg_dict.time) || moment,
  1011. text = msg_dict.message,
  1012. match = text.match(/^\/(.*?)(?: (.*))?$/),
  1013. fullname = msg_dict.fullname || this.model.get('fullname'), // XXX Perhaps always use model's?
  1014. extra_classes = msg_dict.delayed && 'delayed' || '',
  1015. template, username;
  1016. if ((match) && (match[1] === 'me')) {
  1017. text = text.replace(/^\/me/, '');
  1018. template = converse.templates.action;
  1019. username = fullname;
  1020. } else {
  1021. template = converse.templates.message;
  1022. username = msg_dict.sender === 'me' && __('me') || fullname;
  1023. }
  1024. $content.find('div.chat-event').remove();
  1025. if (this.is_chatroom && msg_dict.sender == 'them' && (new RegExp("\\b"+this.model.get('nick')+"\\b")).test(text)) {
  1026. // Add special class to mark groupchat messages in which we
  1027. // are mentioned.
  1028. extra_classes += ' mentioned';
  1029. }
  1030. var message = template({
  1031. 'sender': msg_dict.sender,
  1032. 'time': msg_time.format('hh:mm'),
  1033. 'username': username,
  1034. 'message': '',
  1035. 'extra_classes': extra_classes
  1036. });
  1037. $content.append($(message).children('.chat-message-content').first().text(text).addHyperlinks().addEmoticons().parent());
  1038. this.scrollDown();
  1039. },
  1040. showHelpMessages: function (msgs, type, spinner) {
  1041. var $chat_content = this.$el.find('.chat-content'), i,
  1042. msgs_length = msgs.length;
  1043. for (i=0; i<msgs_length; i++) {
  1044. $chat_content.append($('<div class="chat-'+(type||'info')+'">'+msgs[i]+'</div>'));
  1045. }
  1046. if (spinner === true) {
  1047. $chat_content.append('<span class="spinner"/>');
  1048. } else if (spinner === false) {
  1049. $chat_content.find('span.spinner').remove();
  1050. }
  1051. return this.scrollDown();
  1052. },
  1053. onMessageAdded: function (message) {
  1054. var time = message.get('time'),
  1055. times = this.model.messages.pluck('time'),
  1056. previous_message, idx, this_date, prev_date, text, match;
  1057. // If this message is on a different day than the one received
  1058. // prior, then indicate it on the chatbox.
  1059. idx = _.indexOf(times, time)-1;
  1060. if (idx >= 0) {
  1061. previous_message = this.model.messages.at(idx);
  1062. prev_date = moment(previous_message.get('time'));
  1063. if (prev_date.isBefore(time, 'day')) {
  1064. this_date = moment(time);
  1065. this.$el.find('.chat-content').append(converse.templates.new_day({
  1066. isodate: this_date.format("YYYY-MM-DD"),
  1067. datestring: this_date.format("dddd MMM Do YYYY")
  1068. }));
  1069. }
  1070. }
  1071. if (message.get(COMPOSING)) {
  1072. this.showStatusNotification(message.get('fullname')+' '+__('is typing'));
  1073. return;
  1074. } else if (message.get(PAUSED)) {
  1075. this.showStatusNotification(message.get('fullname')+' '+__('has stopped typing'));
  1076. return;
  1077. } else {
  1078. this.showMessage(_.clone(message.attributes));
  1079. }
  1080. if ((message.get('sender') != 'me') && (converse.windowState == 'blur')) {
  1081. converse.incrementMsgCounter();
  1082. }
  1083. return this.scrollDown();
  1084. },
  1085. sendMessageStanza: function (text) {
  1086. /*
  1087. * Sends the actual XML stanza to the XMPP server.
  1088. */
  1089. // TODO: Look in ChatPartners to see what resources we have for the recipient.
  1090. // if we have one resource, we sent to only that resources, if we have multiple
  1091. // we send to the bare jid.
  1092. var timestamp = (new Date()).getTime();
  1093. var bare_jid = this.model.get('jid');
  1094. var message = $msg({from: converse.connection.jid, to: bare_jid, type: 'chat', id: timestamp})
  1095. .c('body').t(text).up()
  1096. .c('active', {'xmlns': 'http://jabber.org/protocol/chatstates'});
  1097. converse.connection.send(message);
  1098. if (converse.forward_messages) {
  1099. // Forward the message, so that other connected resources are also aware of it.
  1100. var forwarded = $msg({to:converse.bare_jid, type:'chat', id:timestamp})
  1101. .c('forwarded', {xmlns:'urn:xmpp:forward:0'})
  1102. .c('delay', {xmns:'urn:xmpp:delay',stamp:timestamp}).up()
  1103. .cnode(message.tree());
  1104. converse.connection.send(forwarded);
  1105. }
  1106. },
  1107. sendMessage: function (text) {
  1108. var match = text.replace(/^\s*/, "").match(/^\/(.*)\s*$/), msgs;
  1109. if (match) {
  1110. if (match[1] === "clear") {
  1111. return this.clearMessages();
  1112. }
  1113. else if (match[1] === "help") {
  1114. msgs = [
  1115. '<strong>/help</strong>:'+__('Show this menu')+'',
  1116. '<strong>/me</strong>:'+__('Write in the third person')+'',
  1117. '<strong>/clear</strong>:'+__('Remove messages')+''
  1118. ];
  1119. this.showHelpMessages(msgs);
  1120. return;
  1121. } else if ((converse.allow_otr) && (match[1] === "endotr")) {
  1122. return this.endOTR();
  1123. } else if ((converse.allow_otr) && (match[1] === "otr")) {
  1124. return this.model.initiateOTR();
  1125. }
  1126. }
  1127. if (_.contains([UNVERIFIED, VERIFIED], this.model.get('otr_status'))) {
  1128. // Off-the-record encryption is active
  1129. this.model.otr.sendMsg(text);
  1130. this.model.trigger('showSentOTRMessage', text);
  1131. } else {
  1132. // We only save unencrypted messages.
  1133. var fullname = converse.xmppstatus.get('fullname');
  1134. fullname = _.isEmpty(fullname)? converse.bare_jid: fullname;
  1135. this.model.messages.create({
  1136. fullname: fullname,
  1137. sender: 'me',
  1138. time: moment().format(),
  1139. message: text
  1140. });
  1141. this.sendMessageStanza(text);
  1142. }
  1143. },
  1144. keyPressed: function (ev) {
  1145. var $textarea = $(ev.target),
  1146. message, notify, composing;
  1147. if(ev.keyCode == KEY.ENTER) {
  1148. ev.preventDefault();
  1149. message = $textarea.val();
  1150. $textarea.val('').focus();
  1151. if (message !== '') {
  1152. if (this.model.get('chatroom')) {
  1153. this.sendChatRoomMessage(message);
  1154. } else {
  1155. this.sendMessage(message);
  1156. }
  1157. converse.emit('messageSend', message);
  1158. }
  1159. this.$el.data('composing', false);
  1160. } else if (!this.model.get('chatroom')) {
  1161. // composing data is only for single user chat
  1162. composing = this.$el.data('composing');
  1163. if (!composing) {
  1164. if (ev.keyCode != 47) {
  1165. // We don't send composing messages if the message
  1166. // starts with forward-slash.
  1167. notify = $msg({'to':this.model.get('jid'), 'type': 'chat'})
  1168. .c('composing', {'xmlns':'http://jabber.org/protocol/chatstates'});
  1169. converse.connection.send(notify);
  1170. }
  1171. this.$el.data('composing', true);
  1172. }
  1173. }
  1174. },
  1175. onDragResizeStart: function (ev) {
  1176. if (!converse.allow_dragresize) { return true; }
  1177. // Record element attributes for mouseMove().
  1178. this.height = this.$el.children('.box-flyout').height();
  1179. converse.resized_chatbox = this;
  1180. this.prev_pageY = ev.pageY;
  1181. },
  1182. setChatBoxHeight: function (height) {
  1183. if (!this.model.get('minimized')) {
  1184. this.$el.children('.box-flyout')[0].style.height = converse.applyHeightResistance(height)+'px';
  1185. }
  1186. },
  1187. resizeChatBox: function (ev) {
  1188. var diff = ev.pageY - this.prev_pageY;
  1189. if (!diff) { return; }
  1190. this.height -= diff;
  1191. this.prev_pageY = ev.pageY;
  1192. this.setChatBoxHeight(this.height);
  1193. },
  1194. clearMessages: function (ev) {
  1195. if (ev && ev.preventDefault) { ev.preventDefault(); }
  1196. var result = confirm(__("Are you sure you want to clear the messages from this chat box?"));
  1197. if (result === true) {
  1198. this.$el.find('.chat-content').empty();
  1199. this.model.messages.reset();
  1200. this.model.messages.browserStorage._clear();
  1201. }
  1202. return this;
  1203. },
  1204. insertEmoticon: function (ev) {
  1205. ev.stopPropagation();
  1206. this.$el.find('.toggle-smiley ul').slideToggle(200);
  1207. var $textbox = this.$el.find('textarea.chat-textarea');
  1208. var value = $textbox.val();
  1209. var $target = $(ev.target);
  1210. $target = $target.is('a') ? $target : $target.children('a');
  1211. if (value && (value[value.length-1] !== ' ')) {
  1212. value = value + ' ';
  1213. }
  1214. $textbox.focus().val(value+$target.data('emoticon')+' ');
  1215. },
  1216. toggleEmoticonMenu: function (ev) {
  1217. ev.stopPropagation();
  1218. this.$el.find('.toggle-smiley ul').slideToggle(200);
  1219. },
  1220. toggleOTRMenu: function (ev) {
  1221. ev.stopPropagation();
  1222. this.$el.find('.toggle-otr ul').slideToggle(200);
  1223. },
  1224. showOTRError: function (msg) {
  1225. if (msg == 'Message cannot be sent at this time.') {
  1226. this.showHelpMessages(
  1227. [__('Your message could not be sent')], 'error');
  1228. } else if (msg == 'Received an unencrypted message.') {
  1229. this.showHelpMessages(
  1230. [__('We received an unencrypted message')], 'error');
  1231. } else if (msg == 'Received an unreadable encrypted message.') {
  1232. this.showHelpMessages(
  1233. [__('We received an unreadable encrypted message')],
  1234. 'error');
  1235. } else {
  1236. this.showHelpMessages(['Encryption error occured: '+msg], 'error');
  1237. }
  1238. console.log("OTR ERROR:"+msg);
  1239. },
  1240. buddyStartsOTR: function (ev) {
  1241. this.showHelpMessages([__('This user has requested an encrypted session.')]);
  1242. this.model.initiateOTR();
  1243. },
  1244. startOTRFromToolbar: function (ev) {
  1245. $(ev.target).parent().parent().slideUp();
  1246. ev.stopPropagation();
  1247. this.model.initiateOTR();
  1248. },
  1249. endOTR: function (ev) {
  1250. if (typeof ev !== "undefined") {
  1251. ev.preventDefault();
  1252. ev.stopPropagation();
  1253. }
  1254. this.model.endOTR();
  1255. },
  1256. authOTR: function (ev) {
  1257. var scheme = $(ev.target).data().scheme;
  1258. var result, question, answer;
  1259. if (scheme === 'fingerprint') {
  1260. 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.', [
  1261. this.model.get('fullname'),
  1262. converse.xmppstatus.get('fullname')||converse.bare_jid,
  1263. this.model.otr.priv.fingerprint(),
  1264. this.model.otr.their_priv_pk.fingerprint()
  1265. ]
  1266. ));
  1267. if (result === true) {
  1268. this.model.save({'otr_status': VERIFIED});
  1269. } else {
  1270. this.model.save({'otr_status': UNVERIFIED});
  1271. }
  1272. } else if (scheme === 'smp') {
  1273. 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.'));
  1274. question = prompt(__('What is your security question?'));
  1275. if (question) {
  1276. answer = prompt(__('What is the answer to the security question?'));
  1277. this.model.otr.smpSecret(answer, question);
  1278. }
  1279. } else {
  1280. this.showHelpMessages([__('Invalid authentication scheme provided')], 'error');
  1281. }
  1282. },
  1283. toggleCall: function (ev) {
  1284. ev.stopPropagation();
  1285. converse.emit('callButtonClicked', {
  1286. connection: converse.connection,
  1287. model: this.model
  1288. });
  1289. },
  1290. onChange: function (item, changed) {
  1291. if (_.has(item.changed, 'chat_status')) {
  1292. var chat_status = item.get('chat_status'),
  1293. fullname = item.get('fullname');
  1294. fullname = _.isEmpty(fullname)? item.get('jid'): fullname;
  1295. if (this.$el.is(':visible')) {
  1296. if (chat_status === 'offline') {
  1297. this.showStatusNotification(fullname+' '+'has gone offline');
  1298. } else if (chat_status === 'away') {
  1299. this.showStatusNotification(fullname+' '+'has gone away');
  1300. } else if ((chat_status === 'dnd')) {
  1301. this.showStatusNotification(fullname+' '+'is busy');
  1302. } else if (chat_status === 'online') {
  1303. this.$el.find('div.chat-event').remove();
  1304. }
  1305. }
  1306. converse.emit('buddyStatusChanged', item.attributes, item.get('chat_status'));
  1307. }
  1308. if (_.has(item.changed, 'status')) {
  1309. this.showStatusMessage();
  1310. converse.emit('buddyStatusMessageChanged', item.attributes, item.get('status'));
  1311. }
  1312. if (_.has(item.changed, 'image')) {
  1313. this.renderAvatar();
  1314. }
  1315. if (_.has(item.changed, 'otr_status')) {
  1316. this.renderToolbar().informOTRChange();
  1317. }
  1318. if (_.has(item.changed, 'minimized')) {
  1319. if (item.get('minimized')) {
  1320. this.hide();
  1321. } else {
  1322. this.maximize();
  1323. }
  1324. }
  1325. // TODO check for changed fullname as well
  1326. },
  1327. showStatusMessage: function (msg) {
  1328. msg = msg || this.model.get('status');
  1329. if (msg) {
  1330. this.$el.find('p.user-custom-message').text(msg).attr('title', msg);
  1331. }
  1332. return this;
  1333. },
  1334. close: function (ev) {
  1335. if (ev && ev.preventDefault) { ev.preventDefault(); }
  1336. if (converse.connection.connected) {
  1337. this.model.destroy();
  1338. } else {
  1339. this.model.trigger('hide');
  1340. }
  1341. converse.emit('chatBoxClosed', this);
  1342. return this;
  1343. },
  1344. maximize: function () {
  1345. // Restores a minimized chat box
  1346. this.$el.insertAfter(converse.chatboxviews.get("controlbox").$el).show('fast', $.proxy(function () {
  1347. converse.refreshWebkit();
  1348. this.focus();
  1349. converse.emit('chatBoxMaximized', this);
  1350. }, this));
  1351. },
  1352. minimize: function (ev) {
  1353. if (ev && ev.preventDefault) { ev.preventDefault(); }
  1354. // Minimizes a chat box
  1355. this.model.minimize();
  1356. this.$el.hide('fast', converse.refreshwebkit);
  1357. converse.emit('chatBoxMinimized', this);
  1358. },
  1359. updateVCard: function () {
  1360. var jid = this.model.get('jid'),
  1361. contact = converse.roster.get(jid);
  1362. if ((contact) && (!contact.get('vcard_updated'))) {
  1363. converse.getVCard(
  1364. jid,
  1365. $.proxy(function (jid, fullname, image, image_type, url) {
  1366. this.model.save({
  1367. 'fullname' : fullname || jid,
  1368. 'url': url,
  1369. 'image_type': image_type,
  1370. 'image': image
  1371. });
  1372. }, this),
  1373. $.proxy(function (stanza) {
  1374. converse.log("ChatBoxView.initialize: An error occured while fetching vcard");
  1375. }, this)
  1376. );
  1377. }
  1378. },
  1379. informOTRChange: function () {
  1380. var data = this.model.toJSON();
  1381. var msgs = [];
  1382. if (data.otr_status == UNENCRYPTED) {
  1383. msgs.push(__("Your messages are not encrypted anymore"));
  1384. } else if (data.otr_status == UNVERIFIED){
  1385. msgs.push(__("Your messages are now encrypted but your buddy's identity has not been verified."));
  1386. } else if (data.otr_status == VERIFIED){
  1387. msgs.push(__("Your buddy's identify has been verified."));
  1388. } else if (data.otr_status == FINISHED){
  1389. msgs.push(__("Your buddy has ended encryption on their end, you should do the same."));
  1390. }
  1391. return this.showHelpMessages(msgs, 'info', false);
  1392. },
  1393. renderToolbar: function () {
  1394. if (converse.show_toolbar) {
  1395. var data = this.model.toJSON();
  1396. if (data.otr_status == UNENCRYPTED) {
  1397. data.otr_tooltip = __('Your messages are not encrypted. Click here to enable OTR encryption.');
  1398. } else if (data.otr_status == UNVERIFIED){
  1399. data.otr_tooltip = __('Your messages are encrypted, but your buddy has not been verified.');
  1400. } else if (data.otr_status == VERIFIED){
  1401. data.otr_tooltip = __('Your messages are encrypted and your buddy verified.');
  1402. } else if (data.otr_status == FINISHED){
  1403. data.otr_tooltip = __('Your buddy has closed their end of the private session, you should do the same');
  1404. }
  1405. this.$el.find('.chat-toolbar').html(
  1406. converse.templates.toolbar(
  1407. _.extend(data, {
  1408. FINISHED: FINISHED,
  1409. UNENCRYPTED: UNENCRYPTED,
  1410. UNVERIFIED: UNVERIFIED,
  1411. VERIFIED: VERIFIED,
  1412. allow_otr: converse.allow_otr && !this.is_chatroom,
  1413. label_clear: __('Clear all messages'),
  1414. label_end_encrypted_conversation: __('End encrypted conversation'),
  1415. label_hide_participants: __('Hide the list of participants'),
  1416. label_refresh_encrypted_conversation: __('Refresh encrypted conversation'),
  1417. label_start_call: __('Start a call'),
  1418. label_start_encrypted_conversation: __('Start encrypted conversation'),
  1419. label_verify_with_fingerprints: __('Verify with fingerprints'),
  1420. label_verify_with_smp: __('Verify with SMP'),
  1421. label_whats_this: __("What\'s this?"),
  1422. otr_status_class: OTR_CLASS_MAPPING[data.otr_status],
  1423. otr_translated_status: OTR_TRANSLATED_MAPPING[data.otr_status],
  1424. show_call_button: converse.visible_toolbar_buttons.call,
  1425. show_clear_button: converse.visible_toolbar_buttons.clear,
  1426. show_emoticons: converse.visible_toolbar_buttons.emoticons,
  1427. show_participants_toggle: this.is_chatroom && converse.visible_toolbar_buttons.toggle_participants
  1428. })
  1429. )
  1430. );
  1431. }
  1432. return this;
  1433. },
  1434. renderAvatar: function () {
  1435. if (!this.model.get('image')) {
  1436. return;
  1437. }
  1438. var img_src = 'data:'+this.model.get('image_type')+';base64,'+this.model.get('image'),
  1439. canvas = $('<canvas height="31px" width="31px" class="avatar"></canvas>').get(0);
  1440. if (!(canvas.getContext && canvas.getContext('2d'))) {
  1441. return this;
  1442. }
  1443. var ctx = canvas.getContext('2d');
  1444. var img = new Image(); // Create new Image object
  1445. img.onload = function() {
  1446. var ratio = img.width/img.height;
  1447. ctx.drawImage(img, 0,0, 35*ratio, 35);
  1448. };
  1449. img.src = img_src;
  1450. this.$el.find('.chat-title').before(canvas);
  1451. return this;
  1452. },
  1453. focus: function () {
  1454. this.$el.find('.chat-textarea').focus();
  1455. converse.emit('chatBoxFocused', this);
  1456. return this;
  1457. },
  1458. hide: function () {
  1459. if (this.$el.is(':visible') && this.$el.css('opacity') == "1") {
  1460. this.$el.hide();
  1461. converse.refreshWebkit();
  1462. }
  1463. return this;
  1464. },
  1465. show: function (callback) {
  1466. if (this.$el.is(':visible') && this.$el.css('opacity') == "1") {
  1467. return this.focus();
  1468. }
  1469. this.$el.fadeIn(callback);
  1470. if (converse.connection.connected) {
  1471. // Without a connection, we haven't yet initialized
  1472. // localstorage
  1473. this.model.save();
  1474. this.initDragResize();
  1475. }
  1476. return this;
  1477. },
  1478. scrollDown: function () {
  1479. var $content = this.$('.chat-content');
  1480. if ($content.is(':visible')) {
  1481. $content.scrollTop($content[0].scrollHeight);
  1482. }
  1483. return this;
  1484. }
  1485. });
  1486. this.ContactsPanel = Backbone.View.extend({
  1487. tagName: 'div',
  1488. className: 'controlbox-pane',
  1489. id: 'users',
  1490. events: {
  1491. 'click a.toggle-xmpp-contact-form': 'toggleContactForm',
  1492. 'submit form.add-xmpp-contact': 'addContactFromForm',
  1493. 'submit form.search-xmpp-contact': 'searchContacts',
  1494. 'click a.subscribe-to-user': 'addContactFromList'
  1495. },
  1496. initialize: function (cfg) {
  1497. cfg.$parent.append(this.$el);
  1498. this.$tabs = cfg.$parent.parent().find('#controlbox-tabs');
  1499. },
  1500. render: function () {
  1501. var markup;
  1502. var widgets = converse.templates.contacts_panel({
  1503. label_online: __('Online'),
  1504. label_busy: __('Busy'),
  1505. label_away: __('Away'),
  1506. label_offline: __('Offline'),
  1507. label_logout: __('Log out'),
  1508. allow_logout: converse.allow_logout,
  1509. });
  1510. this.$tabs.append(converse.templates.contacts_tab({label_contacts: LABEL_CONTACTS}));
  1511. if (converse.xhr_user_search) {
  1512. markup = converse.templates.search_contact({
  1513. label_contact_name: __('Contact name'),
  1514. label_search: __('Search')
  1515. });
  1516. } else {
  1517. markup = converse.templates.add_contact_form({
  1518. label_contact_username: __('Contact username'),
  1519. label_add: __('Add')
  1520. });
  1521. }
  1522. if (converse.allow_contact_requests) {
  1523. widgets += converse.templates.add_contact_dropdown({
  1524. label_click_to_chat: __('Click to add new chat contacts'),
  1525. label_add_contact: __('Add a contact')
  1526. });
  1527. }
  1528. this.$el.html(widgets);
  1529. this.$el.find('.search-xmpp ul').append(markup);
  1530. return this;
  1531. },
  1532. toggleContactForm: function (ev) {
  1533. ev.preventDefault();
  1534. this.$el.find('.search-xmpp').toggle('fast', function () {
  1535. if ($(this).is(':visible')) {
  1536. $(this).find('input.username').focus();
  1537. }
  1538. });
  1539. },
  1540. searchContacts: function (ev) {
  1541. ev.preventDefault();
  1542. $.getJSON(converse.xhr_user_search_url+ "?q=" + $(ev.target).find('input.username').val(), function (data) {
  1543. var $ul= $('.search-xmpp ul');
  1544. $ul.find('li.found-user').remove();
  1545. $ul.find('li.chat-info').remove();
  1546. if (!data.length) {
  1547. $ul.append('<li class="chat-info">'+__('No users found')+'</li>');
  1548. }
  1549. $(data).each(function (idx, obj) {
  1550. $ul.append(
  1551. $('<li class="found-user"></li>')
  1552. .append(
  1553. $('<a class="subscribe-to-user" href="#" title="'+__('Click to add as a chat contact')+'"></a>')
  1554. .attr('data-recipient', Strophe.escapeNode(obj.id)+'@'+converse.domain)
  1555. .text(obj.fullname)
  1556. )
  1557. );
  1558. });
  1559. });
  1560. },
  1561. addContactFromForm: function (ev) {
  1562. ev.preventDefault();
  1563. var $input = $(ev.target).find('input');
  1564. var jid = $input.val();
  1565. if (! jid) {
  1566. // this is not a valid JID
  1567. $input.addClass('error');
  1568. return;
  1569. }
  1570. this.addContact(jid);
  1571. $('.search-xmpp').hide();
  1572. },
  1573. addContactFromList: function (ev) {
  1574. ev.preventDefault();
  1575. var $target = $(ev.target),
  1576. jid = $target.attr('data-recipient'),
  1577. name = $target.text();
  1578. this.addContact(jid, name);
  1579. $target.parent().remove();
  1580. $('.search-xmpp').hide();
  1581. },
  1582. addContact: function (jid, name) {
  1583. name = _.isEmpty(name)? jid: name;
  1584. converse.connection.roster.add(jid, name, [], function (iq) {
  1585. converse.connection.roster.subscribe(jid, null, converse.xmppstatus.get('fullname'));
  1586. });
  1587. }
  1588. });
  1589. this.RoomsPanel = Backbone.View.extend({
  1590. tagName: 'div',
  1591. id: 'chatrooms',
  1592. events: {
  1593. 'submit form.add-chatroom': 'createChatRoom',
  1594. 'click input#show-rooms': 'showRooms',
  1595. 'click a.open-room': 'createChatRoom',
  1596. 'click a.room-info': 'showRoomInfo'
  1597. },
  1598. initialize: function (cfg) {
  1599. cfg.$parent.append(
  1600. this.$el.html(
  1601. converse.templates.room_panel({
  1602. 'server_input_type': converse.hide_muc_server && 'hidden' || 'text',
  1603. 'label_room_name': __('Room name'),
  1604. 'label_nickname': __('Nickname'),
  1605. 'label_server': __('Server'),
  1606. 'label_join': __('Join'),
  1607. 'label_show_rooms': __('Show rooms')
  1608. })
  1609. ).hide());
  1610. this.$tabs = cfg.$parent.parent().find('#controlbox-tabs');
  1611. this.on('update-rooms-list', function (ev) {
  1612. this.updateRoomsList();
  1613. });
  1614. converse.xmppstatus.on("change", $.proxy(function (model) {
  1615. if (!(_.has(model.changed, 'fullname'))) {
  1616. return;
  1617. }
  1618. var $nick = this.$el.find('input.new-chatroom-nick');
  1619. if (! $nick.is(':focus')) {
  1620. $nick.val(model.get('fullname'));
  1621. }
  1622. }, this));
  1623. },
  1624. render: function () {
  1625. this.$tabs.append(converse.templates.chatrooms_tab({label_rooms: __('Rooms')}));
  1626. return this;
  1627. },
  1628. informNoRoomsFound: function () {
  1629. var $available_chatrooms = this.$el.find('#available-chatrooms');
  1630. // # For translators: %1$s is a variable and will be replaced with the XMPP server name
  1631. $available_chatrooms.html('<dt>'+__('No rooms on %1$s',this.muc_domain)+'</dt>');
  1632. $('input#show-rooms').show().siblings('span.spinner').remove();
  1633. },
  1634. updateRoomsList: function (domain) {
  1635. converse.connection.muc.listRooms(
  1636. this.muc_domain,
  1637. $.proxy(function (iq) { // Success
  1638. var name, jid, i, fragment,
  1639. that = this,
  1640. $available_chatrooms = this.$el.find('#available-chatrooms');
  1641. this.rooms = $(iq).find('query').find('item');
  1642. if (this.rooms.length) {
  1643. // # For translators: %1$s is a variable and will be
  1644. // # replaced with the XMPP server name
  1645. $available_chatrooms.html('<dt>'+__('Rooms on %1$s',this.muc_domain)+'</dt>');
  1646. fragment = document.createDocumentFragment();
  1647. for (i=0; i<this.rooms.length; i++) {
  1648. name = Strophe.unescapeNode($(this.rooms[i]).attr('name')||$(this.rooms[i]).attr('jid'));
  1649. jid = $(this.rooms[i]).attr('jid');
  1650. fragment.appendChild($(
  1651. converse.templates.room_item({
  1652. 'name':name,
  1653. 'jid':jid,
  1654. 'open_title': __('Click to open this room'),
  1655. 'info_title': __('Show more information on this room')
  1656. })
  1657. )[0]);
  1658. }
  1659. $available_chatrooms.append(fragment);
  1660. $('input#show-rooms').show().siblings('span.spinner').remove();
  1661. } else {
  1662. this.informNoRoomsFound();
  1663. }
  1664. return true;
  1665. }, this),
  1666. $.proxy(function (iq) { // Failure
  1667. this.informNoRoomsFound();
  1668. }, this));
  1669. },
  1670. showRooms: function (ev) {
  1671. var $available_chatrooms = this.$el.find('#available-chatrooms');
  1672. var $server = this.$el.find('input.new-chatroom-server');
  1673. var server = $server.val();
  1674. if (!server) {
  1675. $server.addClass('error');
  1676. return;
  1677. }
  1678. this.$el.find('input.new-chatroom-name').removeClass('error');
  1679. $server.removeClass('error');
  1680. $available_chatrooms.empty();
  1681. $('input#show-rooms').hide().after('<span class="spinner"/>');
  1682. this.muc_domain = server;
  1683. this.updateRoomsList();
  1684. },
  1685. showRoomInfo: function (ev) {
  1686. var target = ev.target,
  1687. $dd = $(target).parent('dd'),
  1688. $div = $dd.find('div.room-info');
  1689. if ($div.length) {
  1690. $div.remove();
  1691. } else {
  1692. $dd.find('span.spinner').remove();
  1693. $dd.append('<span class="spinner hor_centered"/>');
  1694. converse.connection.disco.info(
  1695. $(target).attr('data-room-jid'),
  1696. null,
  1697. $.proxy(function (stanza) {
  1698. var $stanza = $(stanza);
  1699. // All MUC features found here: http://xmpp.org/registrar/disco-features.html
  1700. $dd.find('span.spinner').replaceWith(
  1701. converse.templates.room_description({
  1702. 'desc': $stanza.find('field[var="muc#roominfo_description"] value').text(),
  1703. 'occ': $stanza.find('field[var="muc#roominfo_occupants"] value').text(),
  1704. 'hidden': $stanza.find('feature[var="muc_hidden"]').length,
  1705. 'membersonly': $stanza.find('feature[var="muc_membersonly"]').length,
  1706. 'moderated': $stanza.find('feature[var="muc_moderated"]').length,
  1707. 'nonanonymous': $stanza.find('feature[var="muc_nonanonymous"]').length,
  1708. 'open': $stanza.find('feature[var="muc_open"]').length,
  1709. 'passwordprotected': $stanza.find('feature[var="muc_passwordprotected"]').length,
  1710. 'persistent': $stanza.find('feature[var="muc_persistent"]').length,
  1711. 'publicroom': $stanza.find('feature[var="muc_public"]').length,
  1712. 'semianonymous': $stanza.find('feature[var="muc_semianonymous"]').length,
  1713. 'temporary': $stanza.find('feature[var="muc_temporary"]').length,
  1714. 'unmoderated': $stanza.find('feature[var="muc_unmoderated"]').length,
  1715. 'label_desc': __('Description:'),
  1716. 'label_occ': __('Occupants:'),
  1717. 'label_features': __('Features:'),
  1718. 'label_requires_auth': __('Requires authentication'),
  1719. 'label_hidden': __('Hidden'),
  1720. 'label_requires_invite': __('Requires an invitation'),
  1721. 'label_moderated': __('Moderated'),
  1722. 'label_non_anon': __('Non-anonymous'),
  1723. 'label_open_room': __('Open room'),
  1724. 'label_permanent_room': __('Permanent room'),
  1725. 'label_public': __('Public'),
  1726. 'label_semi_anon': _('Semi-anonymous'),
  1727. 'label_temp_room': _('Temporary room'),
  1728. 'label_unmoderated': __('Unmoderated')
  1729. }));
  1730. }, this));
  1731. }
  1732. },
  1733. createChatRoom: function (ev) {
  1734. ev.preventDefault();
  1735. var name, $name,
  1736. server, $server,
  1737. jid,
  1738. $nick = this.$el.find('input.new-chatroom-nick'),
  1739. nick = $nick.val(),
  1740. chatroom;
  1741. if (!nick) { $nick.addClass('error'); }
  1742. else { $nick.removeClass('error'); }
  1743. if (ev.type === 'click') {
  1744. jid = $(ev.target).attr('data-room-jid');
  1745. } else {
  1746. $name = this.$el.find('input.new-chatroom-name');
  1747. $server= this.$el.find('input.new-chatroom-server');
  1748. server = $server.val();
  1749. name = $name.val().trim().toLowerCase();
  1750. $name.val(''); // Clear the input
  1751. if (name && server) {
  1752. jid = Strophe.escapeNode(name) + '@' + server;
  1753. $name.removeClass('error');
  1754. $server.removeClass('error');
  1755. this.muc_domain = server;
  1756. } else {
  1757. if (!name) { $name.addClass('error'); }
  1758. if (!server) { $server.addClass('error'); }
  1759. return;
  1760. }
  1761. }
  1762. if (!nick) { return; }
  1763. chatroom = converse.chatboxviews.showChat({
  1764. 'id': jid,
  1765. 'jid': jid,
  1766. 'name': Strophe.unescapeNode(Strophe.getNodeFromJid(jid)),
  1767. 'nick': nick,
  1768. 'chatroom': true,
  1769. 'box_id' : b64_sha1(jid)
  1770. });
  1771. }
  1772. });
  1773. this.ControlBoxView = converse.ChatBoxView.extend({
  1774. tagName: 'div',
  1775. className: 'chatbox',
  1776. id: 'controlbox',
  1777. events: {
  1778. 'click a.close-chatbox-button': 'close',
  1779. 'click ul#controlbox-tabs li a': 'switchTab',
  1780. 'mousedown .dragresize-tm': 'onDragResizeStart'
  1781. },
  1782. initialize: function () {
  1783. this.$el.insertAfter(converse.controlboxtoggle.$el);
  1784. this.model.on('change:connected', this.onConnected, this);
  1785. this.model.on('destroy', this.hide, this);
  1786. this.model.on('hide', this.hide, this);
  1787. this.model.on('show', this.show, this);
  1788. this.model.on('change:closed', this.ensureClosedState, this);
  1789. this.render();
  1790. if (this.model.get('connected')) {
  1791. this.initRoster();
  1792. }
  1793. if (!this.model.get('closed')) {
  1794. this.show();
  1795. } else {
  1796. this.hide();
  1797. }
  1798. },
  1799. onConnected: function () {
  1800. if (this.model.get('connected')) {
  1801. this.render().initRoster();
  1802. converse.features.off('add', this.featureAdded, this);
  1803. converse.features.on('add', this.featureAdded, this);
  1804. // Features could have been added before the controlbox was
  1805. // initialized. Currently we're only interested in MUC
  1806. var feature = converse.features.findWhere({'var': 'http://jabber.org/protocol/muc'});
  1807. if (feature) {
  1808. this.featureAdded(feature);
  1809. }
  1810. }
  1811. },
  1812. initRoster: function () {
  1813. /* We initialize the roster, which will appear inside the
  1814. * Contacts Panel.
  1815. */
  1816. converse.roster = new converse.RosterContacts();
  1817. converse.roster.browserStorage = new Backbone.BrowserStorage[converse.storage](
  1818. b64_sha1('converse.contacts-'+converse.bare_jid));
  1819. var rostergroups = new converse.RosterGroups();
  1820. rostergroups.browserStorage = new Backbone.BrowserStorage[converse.storage](
  1821. b64_sha1('converse.roster.groups'+converse.bare_jid));
  1822. converse.rosterview = new converse.RosterView({model: rostergroups});
  1823. this.contactspanel.$el.append(converse.rosterview.$el);
  1824. converse.rosterview.render().fetch().update();
  1825. converse.connection.roster.get(function () {});
  1826. return this;
  1827. },
  1828. render: function () {
  1829. if (!converse.connection.connected || !converse.connection.authenticated || converse.connection.disconnecting) {
  1830. // TODO: we might need to take prebinding into consideration here.
  1831. this.renderLoginPanel();
  1832. } else if (!this.contactspanel || !this.contactspanel.$el.is(':visible')) {
  1833. this.renderContactsPanel();
  1834. }
  1835. return this;
  1836. },
  1837. renderLoginPanel: function () {
  1838. this.$el.html(converse.templates.controlbox(this.model.toJSON()));
  1839. var cfg = {'$parent': this.$el.find('.controlbox-panes'), 'model': this};
  1840. if (!this.loginpanel) {
  1841. this.loginpanel = new converse.LoginPanel(cfg);
  1842. } else {
  1843. this.loginpanel.delegateEvents().initialize(cfg);
  1844. }
  1845. this.loginpanel.render();
  1846. this.initDragResize();
  1847. },
  1848. renderContactsPanel: function () {
  1849. this.$el.html(converse.templates.controlbox(this.model.toJSON()));
  1850. this.contactspanel = new converse.ContactsPanel({'$parent': this.$el.find('.controlbox-panes')});
  1851. this.contactspanel.render();
  1852. converse.xmppstatusview = new converse.XMPPStatusView({'model': converse.xmppstatus});
  1853. converse.xmppstatusview.render();
  1854. if (converse.allow_muc) {
  1855. this.roomspanel = new converse.RoomsPanel({'$parent': this.$el.find('.controlbox-panes')});
  1856. this.roomspanel.render();
  1857. }
  1858. this.initDragResize();
  1859. },
  1860. close: function (ev) {
  1861. if (ev && ev.preventDefault) { ev.preventDefault(); }
  1862. if (converse.connection.connected) {
  1863. this.model.save({'closed': true});
  1864. } else {
  1865. this.model.trigger('hide');
  1866. }
  1867. converse.emit('controlBoxClosed', this);
  1868. return this;
  1869. },
  1870. ensureClosedState: function () {
  1871. if (this.model.get('closed')) {
  1872. this.hide();
  1873. } else {
  1874. this.show();
  1875. }
  1876. },
  1877. hide: function (callback) {
  1878. this.$el.hide('fast', function () {
  1879. converse.refreshWebkit();
  1880. converse.emit('chatBoxClosed', this);
  1881. converse.controlboxtoggle.show(function () {
  1882. if (typeof callback === "function") {
  1883. callback();
  1884. }
  1885. });
  1886. });
  1887. return this;
  1888. },
  1889. show: function () {
  1890. converse.controlboxtoggle.hide($.proxy(function () {
  1891. this.$el.show('fast', function () {
  1892. if (converse.rosterview) {
  1893. converse.rosterview.update();
  1894. }
  1895. converse.refreshWebkit();
  1896. }.bind(this));
  1897. converse.emit('controlBoxOpened', this);
  1898. }, this));
  1899. return this;
  1900. },
  1901. featureAdded: function (feature) {
  1902. if ((feature.get('var') == 'http://jabber.org/protocol/muc') && (converse.allow_muc)) {
  1903. this.roomspanel.muc_domain = feature.get('from');
  1904. var $server= this.$el.find('input.new-chatroom-server');
  1905. if (! $server.is(':focus')) {
  1906. $server.val(this.roomspanel.muc_domain);
  1907. }
  1908. if (converse.auto_list_rooms) {
  1909. this.roomspanel.trigger('update-rooms-list');
  1910. }
  1911. }
  1912. },
  1913. switchTab: function (ev) {
  1914. ev.preventDefault();
  1915. var $tab = $(ev.target),
  1916. $sibling = $tab.parent().siblings('li').children('a'),
  1917. $tab_panel = $($tab.attr('href'));
  1918. $($sibling.attr('href')).hide();
  1919. $sibling.removeClass('current');
  1920. $tab.addClass('current');
  1921. $tab_panel.show();
  1922. },
  1923. showHelpMessages: function (msgs) {
  1924. // Override showHelpMessages in ChatBoxView, for now do nothing.
  1925. return;
  1926. }
  1927. });
  1928. this.ChatRoomOccupant = Backbone.Model;
  1929. this.ChatRoomOccupantView = Backbone.View.extend({
  1930. tagName: 'li',
  1931. initialize: function () {
  1932. this.model.on('change', this.render, this);
  1933. this.model.on('destroy', this.destroy, this);
  1934. },
  1935. render: function () {
  1936. var $new = converse.templates.occupant(
  1937. _.extend(
  1938. this.model.toJSON(), {
  1939. 'desc_moderator': __('This user is a moderator'),
  1940. 'desc_participant': __('This user can send messages in this room'),
  1941. 'desc_visitor': __('This user can NOT send messages in this room')
  1942. })
  1943. );
  1944. this.$el.replaceWith($new);
  1945. this.setElement($new, true);
  1946. return this;
  1947. },
  1948. destroy: function () {
  1949. this.$el.remove();
  1950. }
  1951. });
  1952. this.ChatRoomOccupants = Backbone.Collection.extend({
  1953. model: converse.ChatRoomOccupant,
  1954. initialize: function (options) {
  1955. this.browserStorage = new Backbone.BrowserStorage[converse.storage](
  1956. b64_sha1('converse.occupants'+converse.bare_jid+options.nick));
  1957. },
  1958. });
  1959. this.ChatRoomOccupantsView = Backbone.Overview.extend({
  1960. tagName: 'div',
  1961. className: 'participants',
  1962. initialize: function () {
  1963. this.model.on("add", this.onOccupantAdded, this);
  1964. },
  1965. render: function () {
  1966. this.$el.html(
  1967. converse.templates.chatroom_sidebar({
  1968. 'label_invitation': __('Invite...'),
  1969. 'label_occupants': __('Occupants')
  1970. })
  1971. );
  1972. return this.initInviteWidget();
  1973. },
  1974. onOccupantAdded: function (item) {
  1975. var view = this.get(item.get('id'));
  1976. if (!view) {
  1977. view = this.add(item.get('id'), new converse.ChatRoomOccupantView({model: item}));
  1978. } else {
  1979. delete view.model; // Remove ref to old model to help garbage collection
  1980. view.model = item;
  1981. view.initialize();
  1982. }
  1983. this.$('.participant-list').append(view.render().$el);
  1984. },
  1985. onChatRoomRoster: function (roster, room) {
  1986. var roster_size = _.size(roster),
  1987. $participant_list = this.$('.participant-list'),
  1988. participants = [],
  1989. keys = _.keys(roster),
  1990. occupant, attrs, i, nick;
  1991. for (i=0; i<roster_size; i++) {
  1992. nick = Strophe.unescapeNode(keys[i]);
  1993. attrs = {
  1994. 'id': nick,
  1995. 'role': roster[keys[i]].role,
  1996. 'nick': nick
  1997. };
  1998. occupant = this.model.get(nick);
  1999. if (occupant) {
  2000. occupant.save(attrs);
  2001. } else {
  2002. this.model.create(attrs);
  2003. }
  2004. }
  2005. _.each(_.difference(this.model.pluck('id'), keys), function (id) {
  2006. this.model.get(id).destroy();
  2007. }, this);
  2008. return true;
  2009. },
  2010. initInviteWidget: function () {
  2011. var $el = this.$('input.invited-contact');
  2012. $el.typeahead({
  2013. minLength: 1,
  2014. highlight: true
  2015. }, {
  2016. name: 'contacts-dataset',
  2017. source: function (q, cb) {
  2018. var results = [];
  2019. _.each(converse.roster.filter(contains(['fullname', 'jid'], q)), function (n) {
  2020. results.push({value: n.get('fullname'), jid: n.get('jid')});
  2021. });
  2022. cb(results);
  2023. },
  2024. templates: {
  2025. suggestion: _.template('<p data-jid="{{jid}}">{{value}}</p>')
  2026. }
  2027. });
  2028. $el.on('typeahead:selected', $.proxy(function (ev, suggestion, dname) {
  2029. var reason = prompt(
  2030. __(___('You are about to invite %1$s to the chat room "%2$s". '), suggestion.value, this.model.get('id')) +
  2031. __("You may optionally include a message, explaining the reason for the invitation.")
  2032. );
  2033. if (reason !== null) {
  2034. converse.connection.muc.rooms[this.chatroomview.model.get('id')].directInvite(suggestion.jid, reason);
  2035. converse.emit('roomInviteSent', this, suggestion.jid, reason);
  2036. }
  2037. $(ev.target).typeahead('val', '');
  2038. }, this));
  2039. return this;
  2040. },
  2041. });
  2042. this.ChatRoomView = converse.ChatBoxView.extend({
  2043. length: 300,
  2044. tagName: 'div',
  2045. className: 'chatroom',
  2046. events: {
  2047. 'click .close-chatbox-button': 'close',
  2048. 'click .toggle-chatbox-button': 'minimize',
  2049. 'click .configure-chatroom-button': 'configureChatRoom',
  2050. 'click .toggle-smiley': 'toggleEmoticonMenu',
  2051. 'click .toggle-smiley ul li': 'insertEmoticon',
  2052. 'click .toggle-clear': 'clearChatRoomMessages',
  2053. 'click .toggle-participants a': 'toggleOccupants',
  2054. 'keypress textarea.chat-textarea': 'keyPressed',
  2055. 'mousedown .dragresize-tm': 'onDragResizeStart'
  2056. },
  2057. is_chatroom: true,
  2058. initialize: function () {
  2059. this.model.messages.on('add', this.onMessageAdded, this);
  2060. this.model.on('change:minimized', function (item) {
  2061. if (item.get('minimized')) {
  2062. this.hide();
  2063. } else {
  2064. this.maximize();
  2065. }
  2066. }, this);
  2067. this.model.on('destroy', function (model, response, options) {
  2068. this.hide();
  2069. converse.connection.muc.leave(
  2070. this.model.get('jid'),
  2071. this.model.get('nick'),
  2072. $.proxy(this.onLeave, this),
  2073. undefined);
  2074. },
  2075. this);
  2076. this.occupantsview = new converse.ChatRoomOccupantsView({
  2077. model: new converse.ChatRoomOccupants({nick: this.model.get('nick')}),
  2078. });
  2079. this.occupantsview.chatroomview = this;
  2080. this.render();
  2081. this.occupantsview.model.fetch({add:true});
  2082. this.connect(null);
  2083. converse.emit('chatRoomOpened', this);
  2084. this.$el.insertAfter(converse.chatboxviews.get("controlbox").$el);
  2085. this.model.messages.fetch({add: true});
  2086. if (this.model.get('minimized')) {
  2087. this.hide();
  2088. } else {
  2089. this.show();
  2090. }
  2091. },
  2092. render: function () {
  2093. this.$el.attr('id', this.model.get('box_id'))
  2094. .html(converse.templates.chatroom(this.model.toJSON()));
  2095. this.renderChatArea();
  2096. setTimeout(function () {
  2097. converse.refreshWebkit();
  2098. }, 50);
  2099. return this;
  2100. },
  2101. renderChatArea: function () {
  2102. if (!this.$('.chat-area').length) {
  2103. this.$('.chat-body').empty()
  2104. .append(
  2105. converse.templates.chatarea({
  2106. 'show_toolbar': converse.show_toolbar,
  2107. 'label_message': __('Message'),
  2108. }))
  2109. .append(this.occupantsview.render().$el);
  2110. this.renderToolbar();
  2111. }
  2112. // XXX: This is a bit of a hack, to make sure that the
  2113. // sidebar's state is remembered.
  2114. this.model.set({hidden_occupants: !this.model.get('hidden_occupants')});
  2115. this.toggleOccupants();
  2116. return this;
  2117. },
  2118. toggleOccupants: function (ev) {
  2119. if (ev) {
  2120. ev.preventDefault();
  2121. ev.stopPropagation();
  2122. }
  2123. var $el = this.$('.icon-hide-users');
  2124. if (!this.model.get('hidden_occupants')) {
  2125. this.model.save({hidden_occupants: true});
  2126. $el.removeClass('icon-hide-users').addClass('icon-show-users');
  2127. this.$('div.participants').animate({width: 0}).hide();
  2128. this.$('.chat-area').animate({width: '100%'}, $.proxy(function () {
  2129. this.scrollDown();
  2130. }, this));
  2131. this.$('form.sendXMPPMessage').animate({width: '100%'});
  2132. } else {
  2133. this.model.save({hidden_occupants: false});
  2134. $el.removeClass('icon-show-users').addClass('icon-hide-users');
  2135. this.$('.chat-area').animate({width: '200px'}, $.proxy(function () {
  2136. this.$('div.participants').css({width: '100px'}).show();
  2137. this.scrollDown();
  2138. }, this));
  2139. this.$('form.sendXMPPMessage').animate({width: '200px'});
  2140. }
  2141. },
  2142. onCommandError: function (stanza) {
  2143. this.showStatusNotification(__("Error: could not execute the command"), true);
  2144. },
  2145. sendChatRoomMessage: function (body) {
  2146. var match = body.replace(/^\s*/, "").match(/^\/(.*?)(?: (.*))?$/) || [false],
  2147. $chat_content, args;
  2148. switch (match[1]) {
  2149. case 'ban':
  2150. args = match[2].splitOnce(' ');
  2151. converse.connection.muc.ban(this.model.get('jid'), args[0], args[1], undefined, $.proxy(this.onCommandError, this));
  2152. break;
  2153. case 'clear':
  2154. this.clearChatRoomMessages();
  2155. break;
  2156. case 'deop':
  2157. args = match[2].splitOnce(' ');
  2158. converse.connection.muc.deop(this.model.get('jid'), args[0], args[1], undefined, $.proxy(this.onCommandError, this));
  2159. break;
  2160. case 'help':
  2161. $chat_content = this.$el.find('.chat-content');
  2162. msgs = [
  2163. '<strong>/ban</strong>: ' +__('Ban user from room'),
  2164. '<strong>/clear</strong>: ' +__('Remove messages'),
  2165. '<strong>/help</strong>: ' +__('Show this menu'),
  2166. '<strong>/kick</strong>: ' +__('Kick user from room'),
  2167. '<strong>/me</strong>: ' +__('Write in 3rd person'),
  2168. '<strong>/mute</strong>: ' +__("Remove user's ability to post messages"),
  2169. '<strong>/nick</strong>: ' +__('Change your nickname'),
  2170. '<strong>/topic</strong>: ' +__('Set room topic'),
  2171. '<strong>/voice</strong>: ' +__('Allow muted user to post messages')
  2172. ];
  2173. this.showHelpMessages(msgs);
  2174. break;
  2175. case 'kick':
  2176. args = match[2].splitOnce(' ');
  2177. converse.connection.muc.kick(this.model.get('jid'), args[0], args[1], undefined, $.proxy(this.onCommandError, this));
  2178. break;
  2179. case 'mute':
  2180. args = match[2].splitOnce(' ');
  2181. converse.connection.muc.mute(this.model.get('jid'), args[0], args[1], undefined, $.proxy(this.onCommandError, this));
  2182. break;
  2183. case 'nick':
  2184. converse.connection.muc.changeNick(this.model.get('jid'), match[2]);
  2185. break;
  2186. case 'op':
  2187. args = match[2].splitOnce(' ');
  2188. converse.connection.muc.op(this.model.get('jid'), args[0], args[1], undefined, $.proxy(this.onCommandError, this));
  2189. break;
  2190. case 'topic':
  2191. converse.connection.muc.setTopic(this.model.get('jid'), match[2]);
  2192. break;
  2193. case 'voice':
  2194. args = match[2].splitOnce(' ');
  2195. converse.connection.muc.voice(this.model.get('jid'), args[0], args[1], undefined, $.proxy(this.onCommandError, this));
  2196. break;
  2197. default:
  2198. this.last_msgid = converse.connection.muc.groupchat(this.model.get('jid'), body);
  2199. break;
  2200. }
  2201. },
  2202. connect: function (password) {
  2203. if (_.has(converse.connection.muc.rooms, this.model.get('jid'))) {
  2204. // If the room exists, it already has event listeners, so we
  2205. // don't add them again.
  2206. converse.connection.muc.join(
  2207. this.model.get('jid'), this.model.get('nick'), null, null, null, password);
  2208. } else {
  2209. converse.connection.muc.join(
  2210. this.model.get('jid'),
  2211. this.model.get('nick'),
  2212. $.proxy(this.onChatRoomMessage, this),
  2213. $.proxy(this.onChatRoomPresence, this),
  2214. $.proxy(this.onChatRoomRoster, this),
  2215. password);
  2216. }
  2217. },
  2218. onLeave: function () {
  2219. this.model.set('connected', false);
  2220. },
  2221. renderConfigurationForm: function (stanza) {
  2222. var $form= this.$el.find('form.chatroom-form'),
  2223. $stanza = $(stanza),
  2224. $fields = $stanza.find('field'),
  2225. title = $stanza.find('title').text(),
  2226. instructions = $stanza.find('instructions').text(),
  2227. i, j, options=[], $field, $options;
  2228. var input_types = {
  2229. 'text-private': 'password',
  2230. 'text-single': 'textline',
  2231. 'boolean': 'checkbox',
  2232. 'hidden': 'hidden',
  2233. 'list-single': 'dropdown'
  2234. };
  2235. $form.find('span.spinner').remove();
  2236. $form.append($('<legend>').text(title));
  2237. if (instructions != title) {
  2238. $form.append($('<p>').text(instructions));
  2239. }
  2240. for (i=0; i<$fields.length; i++) {
  2241. $field = $($fields[i]);
  2242. if ($field.attr('type') == 'list-single') {
  2243. options = [];
  2244. $options = $field.find('option');
  2245. for (j=0; j<$options.length; j++) {
  2246. options.push(converse.templates.select_option({
  2247. value: $($options[j]).find('value').text(),
  2248. label: $($options[j]).attr('label')
  2249. }));
  2250. }
  2251. $form.append(converse.templates.form_select({
  2252. name: $field.attr('var'),
  2253. label: $field.attr('label'),
  2254. options: options.join('')
  2255. }));
  2256. } else if ($field.attr('type') == 'boolean') {
  2257. $form.append(converse.templates.form_checkbox({
  2258. name: $field.attr('var'),
  2259. type: input_types[$field.attr('type')],
  2260. label: $field.attr('label') || '',
  2261. checked: $field.find('value').text() === "1" && 'checked="1"' || ''
  2262. }));
  2263. } else {
  2264. $form.append(converse.templates.form_input({
  2265. name: $field.attr('var'),
  2266. type: input_types[$field.attr('type')],
  2267. label: $field.attr('label') || '',
  2268. value: $field.find('value').text()
  2269. }));
  2270. }
  2271. }
  2272. $form.append('<input type="submit" value="'+__('Save')+'"/>');
  2273. $form.append('<input type="button" value="'+__('Cancel')+'"/>');
  2274. $form.on('submit', $.proxy(this.saveConfiguration, this));
  2275. $form.find('input[type=button]').on('click', $.proxy(this.cancelConfiguration, this));
  2276. },
  2277. saveConfiguration: function (ev) {
  2278. ev.preventDefault();
  2279. var that = this;
  2280. var $inputs = $(ev.target).find(':input:not([type=button]):not([type=submit])'),
  2281. count = $inputs.length,
  2282. configArray = [];
  2283. $inputs.each(function () {
  2284. var $input = $(this), value;
  2285. if ($input.is('[type=checkbox]')) {
  2286. value = $input.is(':checked') && 1 || 0;
  2287. } else {
  2288. value = $input.val();
  2289. }
  2290. var cnode = $(converse.templates.field({
  2291. name: $input.attr('name'),
  2292. value: value
  2293. }))[0];
  2294. configArray.push(cnode);
  2295. if (!--count) {
  2296. converse.connection.muc.saveConfiguration(
  2297. that.model.get('jid'),
  2298. configArray,
  2299. $.proxy(that.onConfigSaved, that),
  2300. $.proxy(that.onErrorConfigSaved, that)
  2301. );
  2302. }
  2303. });
  2304. this.$el.find('div.chatroom-form-container').hide(
  2305. function () {
  2306. $(this).remove();
  2307. that.$el.find('.chat-area').show();
  2308. that.$el.find('.participants').show();
  2309. });
  2310. },
  2311. onConfigSaved: function (stanza) {
  2312. // XXX
  2313. },
  2314. onErrorConfigSaved: function (stanza) {
  2315. this.showStatusNotification(__("An error occurred while trying to save the form."));
  2316. },
  2317. cancelConfiguration: function (ev) {
  2318. ev.preventDefault();
  2319. var that = this;
  2320. this.$el.find('div.chatroom-form-container').hide(
  2321. function () {
  2322. $(this).remove();
  2323. that.$el.find('.chat-area').show();
  2324. that.$el.find('.participants').show();
  2325. });
  2326. },
  2327. configureChatRoom: function (ev) {
  2328. ev.preventDefault();
  2329. if (this.$el.find('div.chatroom-form-container').length) {
  2330. return;
  2331. }
  2332. this.$('.chat-body').children().hide();
  2333. this.$('.chat-body').append(
  2334. $('<div class="chatroom-form-container">'+
  2335. '<form class="chatroom-form">'+
  2336. '<span class="spinner centered"/>'+
  2337. '</form>'+
  2338. '</div>'));
  2339. converse.connection.muc.configure(
  2340. this.model.get('jid'),
  2341. $.proxy(this.renderConfigurationForm, this)
  2342. );
  2343. },
  2344. submitPassword: function (ev) {
  2345. ev.preventDefault();
  2346. var password = this.$el.find('.chatroom-form').find('input[type=password]').val();
  2347. this.$el.find('.chatroom-form-container').replaceWith('<span class="spinner centered"/>');
  2348. this.connect(password);
  2349. },
  2350. renderPasswordForm: function () {
  2351. this.$('.chat-body').children().hide();
  2352. this.$('span.centered.spinner').remove();
  2353. this.$('.chat-body').append(
  2354. converse.templates.chatroom_password_form({
  2355. heading: __('This chatroom requires a password'),
  2356. label_password: __('Password: '),
  2357. label_submit: __('Submit')
  2358. }));
  2359. this.$('.chatroom-form').on('submit', $.proxy(this.submitPassword, this));
  2360. },
  2361. showDisconnectMessage: function (msg) {
  2362. this.$('.chat-area').hide();
  2363. this.$('.participants').hide();
  2364. this.$('span.centered.spinner').remove();
  2365. this.$('.chat-body').append($('<p>'+msg+'</p>'));
  2366. },
  2367. /* http://xmpp.org/extensions/xep-0045.html
  2368. * ----------------------------------------
  2369. * 100 message Entering a room Inform user that any occupant is allowed to see the user's full JID
  2370. * 101 message (out of band) Affiliation change Inform user that his or her affiliation changed while not in the room
  2371. * 102 message Configuration change Inform occupants that room now shows unavailable members
  2372. * 103 message Configuration change Inform occupants that room now does not show unavailable members
  2373. * 104 message Configuration change Inform occupants that a non-privacy-related room configuration change has occurred
  2374. * 110 presence Any room presence Inform user that presence refers to one of its own room occupants
  2375. * 170 message or initial presence Configuration change Inform occupants that room logging is now enabled
  2376. * 171 message Configuration change Inform occupants that room logging is now disabled
  2377. * 172 message Configuration change Inform occupants that the room is now non-anonymous
  2378. * 173 message Configuration change Inform occupants that the room is now semi-anonymous
  2379. * 174 message Configuration change Inform occupants that the room is now fully-anonymous
  2380. * 201 presence Entering a room Inform user that a new room has been created
  2381. * 210 presence Entering a room Inform user that the service has assigned or modified the occupant's roomnick
  2382. * 301 presence Removal from room Inform user that he or she has been banned from the room
  2383. * 303 presence Exiting a room Inform all occupants of new room nickname
  2384. * 307 presence Removal from room Inform user that he or she has been kicked from the room
  2385. * 321 presence Removal from room Inform user that he or she is being removed from the room because of an affiliation change
  2386. * 322 presence Removal from room Inform user that he or she is being removed from the room because the room has been changed to members-only and the user is not a member
  2387. * 332 presence Removal from room Inform user that he or she is being removed from the room because of a system shutdown
  2388. */
  2389. infoMessages: {
  2390. 100: __('This room is not anonymous'),
  2391. 102: __('This room now shows unavailable members'),
  2392. 103: __('This room does not show unavailable members'),
  2393. 104: __('Non-privacy-related room configuration has changed'),
  2394. 170: __('Room logging is now enabled'),
  2395. 171: __('Room logging is now disabled'),
  2396. 172: __('This room is now non-anonymous'),
  2397. 173: __('This room is now semi-anonymous'),
  2398. 174: __('This room is now fully-anonymous'),
  2399. 201: __('A new room has been created'),
  2400. },
  2401. disconnectMessages: {
  2402. 301: __('You have been banned from this room'),
  2403. 307: __('You have been kicked from this room'),
  2404. 321: __("You have been removed from this room because of an affiliation change"),
  2405. 322: __("You have been removed from this room because the room has changed to members-only and you're not a member"),
  2406. 332: __("You have been removed from this room because the MUC (Multi-user chat) service is being shut down.")
  2407. },
  2408. actionInfoMessages: {
  2409. /* XXX: Note the triple underscore function and not double
  2410. * underscore.
  2411. *
  2412. * This is a hack. We can't pass the strings to __ because we
  2413. * don't yet know what the variable to interpolate is.
  2414. *
  2415. * Triple underscore will just return the string again, but we
  2416. * can then at least tell gettext to scan for it so that these
  2417. * strings are picked up by the translation machinery.
  2418. */
  2419. 301: ___("<strong>%1$s</strong> has been banned"),
  2420. 303: ___("<strong>%1$s</strong>'s nickname has changed"),
  2421. 307: ___("<strong>%1$s</strong> has been kicked out"),
  2422. 321: ___("<strong>%1$s</strong> has been removed because of an affiliation change"),
  2423. 322: ___("<strong>%1$s</strong> has been removed for not being a member")
  2424. },
  2425. newNicknameMessages: {
  2426. 210: ___('Your nickname has been automatically changed to: <strong>%1$s</strong>'),
  2427. 303: ___('Your nickname has been changed to: <strong>%1$s</strong>')
  2428. },
  2429. showStatusMessages: function ($el, is_self) {
  2430. /* Check for status codes and communicate their purpose to the user.
  2431. * Allow user to configure chat room if they are the owner.
  2432. * See: http://xmpp.org/registrar/mucstatus.html
  2433. */
  2434. var $chat_content,
  2435. disconnect_msgs = [],
  2436. msgs = [],
  2437. reasons = [];
  2438. $el.find('x[xmlns="'+Strophe.NS.MUC_USER+'"]').each($.proxy(function (idx, x) {
  2439. var $item = $(x).find('item');
  2440. if (Strophe.getBareJidFromJid($item.attr('jid')) === converse.bare_jid && $item.attr('affiliation') === 'owner') {
  2441. this.$el.find('a.configure-chatroom-button').show();
  2442. }
  2443. $(x).find('item reason').each(function (idx, reason) {
  2444. if ($(reason).text()) {
  2445. reasons.push($(reason).text());
  2446. }
  2447. });
  2448. $(x).find('status').each($.proxy(function (idx, stat) {
  2449. var code = stat.getAttribute('code');
  2450. if (is_self && _.contains(_.keys(this.newNicknameMessages), code)) {
  2451. this.model.save({'nick': Strophe.getResourceFromJid($el.attr('from'))});
  2452. msgs.push(__(this.newNicknameMessages[code], $item.attr('nick')));
  2453. } else if (is_self && _.contains(_.keys(this.disconnectMessages), code)) {
  2454. disconnect_msgs.push(this.disconnectMessages[code]);
  2455. } else if (!is_self && _.contains(_.keys(this.actionInfoMessages), code)) {
  2456. msgs.push(
  2457. __(this.actionInfoMessages[code], Strophe.unescapeNode(Strophe.getResourceFromJid($el.attr('from'))))
  2458. );
  2459. } else if (_.contains(_.keys(this.infoMessages), code)) {
  2460. msgs.push(this.infoMessages[code]);
  2461. } else if (code !== '110') {
  2462. if ($(stat).text()) {
  2463. msgs.push($(stat).text()); // Sometimes the status contains human readable text and not a code.
  2464. }
  2465. }
  2466. }, this));
  2467. }, this));
  2468. if (disconnect_msgs.length > 0) {
  2469. for (i=0; i<disconnect_msgs.length; i++) {
  2470. this.showDisconnectMessage(disconnect_msgs[i]);
  2471. }
  2472. for (i=0; i<reasons.length; i++) {
  2473. this.showDisconnectMessage(__('The reason given is: "'+reasons[i]+'"'), true);
  2474. }
  2475. this.model.set('connected', false);
  2476. return;
  2477. }
  2478. $chat_content = this.$el.find('.chat-content');
  2479. for (i=0; i<msgs.length; i++) {
  2480. $chat_content.append(converse.templates.info({message: msgs[i]}));
  2481. }
  2482. for (i=0; i<reasons.length; i++) {
  2483. this.showStatusNotification(__('The reason given is: "'+reasons[i]+'"'), true);
  2484. }
  2485. return this.scrollDown();
  2486. },
  2487. showErrorMessage: function ($error, room) {
  2488. // We didn't enter the room, so we must remove it from the MUC
  2489. // add-on
  2490. delete converse.connection.muc[room.name];
  2491. if ($error.attr('type') == 'auth') {
  2492. if ($error.find('not-authorized').length) {
  2493. this.renderPasswordForm();
  2494. } else if ($error.find('registration-required').length) {
  2495. this.showDisconnectMessage(__('You are not on the member list of this room'));
  2496. } else if ($error.find('forbidden').length) {
  2497. this.showDisconnectMessage(__('You have been banned from this room'));
  2498. }
  2499. } else if ($error.attr('type') == 'modify') {
  2500. if ($error.find('jid-malformed').length) {
  2501. this.showDisconnectMessage(__('No nickname was specified'));
  2502. }
  2503. } else if ($error.attr('type') == 'cancel') {
  2504. if ($error.find('not-allowed').length) {
  2505. this.showDisconnectMessage(__('You are not allowed to create new rooms'));
  2506. } else if ($error.find('not-acceptable').length) {
  2507. this.showDisconnectMessage(__("Your nickname doesn't conform to this room's policies"));
  2508. } else if ($error.find('conflict').length) {
  2509. // TODO: give user the option of choosing a different
  2510. // nickname
  2511. this.showDisconnectMessage(__("Your nickname is already taken"));
  2512. } else if ($error.find('item-not-found').length) {
  2513. this.showDisconnectMessage(__("This room does not (yet) exist"));
  2514. } else if ($error.find('service-unavailable').length) {
  2515. this.showDisconnectMessage(__("This room has reached it's maximum number of occupants"));
  2516. }
  2517. }
  2518. },
  2519. onChatRoomPresence: function (presence, room) {
  2520. var $presence = $(presence), is_self;
  2521. if ($presence.attr('type') === 'error') {
  2522. this.model.set('connected', false);
  2523. this.showErrorMessage($presence.find('error'), room);
  2524. } else {
  2525. is_self = ($presence.find("status[code='110']").length) || ($presence.attr('from') == room.name+'/'+Strophe.escapeNode(room.nick));
  2526. if (!this.model.get('conneced')) {
  2527. this.model.set('connected', true);
  2528. this.$('span.centered.spinner').remove();
  2529. this.$el.find('.chat-body').children().show();
  2530. }
  2531. this.showStatusMessages($presence, is_self);
  2532. }
  2533. return true;
  2534. },
  2535. onChatRoomMessage: function (message) {
  2536. var $message = $(message),
  2537. body = $message.children('body').text(),
  2538. jid = $message.attr('from'),
  2539. resource = Strophe.getResourceFromJid(jid),
  2540. sender = resource && Strophe.unescapeNode(resource) || '',
  2541. delayed = $message.find('delay').length > 0,
  2542. subject = $message.children('subject').text();
  2543. this.showStatusMessages($message);
  2544. if (subject) {
  2545. this.$el.find('.chatroom-topic').text(subject).attr('title', subject);
  2546. // # For translators: the %1$s and %2$s parts will get replaced by the user and topic text respectively
  2547. // # Example: Topic set by JC Brand to: Hello World!
  2548. this.$el.find('.chat-content').append(
  2549. converse.templates.info({
  2550. 'message': __('Topic set by %1$s to: %2$s', sender, subject)
  2551. }));
  2552. }
  2553. if (sender === '') {
  2554. return true;
  2555. }
  2556. this.model.createMessage($message);
  2557. if (!delayed && sender !== this.model.get('nick') && (new RegExp("\\b"+this.model.get('nick')+"\\b")).test(body)) {
  2558. playNotification();
  2559. }
  2560. if (sender !== this.model.get('nick')) {
  2561. // We only emit an event if it's not our own message
  2562. converse.emit('message', message);
  2563. }
  2564. return true;
  2565. },
  2566. onChatRoomRoster: function (roster, room) {
  2567. return this.occupantsview.onChatRoomRoster(roster, room);
  2568. }
  2569. });
  2570. this.ChatBoxes = Backbone.Collection.extend({
  2571. model: converse.ChatBox,
  2572. comparator: 'time_opened',
  2573. registerMessageHandler: function () {
  2574. converse.connection.addHandler(
  2575. $.proxy(function (message) {
  2576. this.onMessage(message);
  2577. return true;
  2578. }, this), null, 'message', 'chat');
  2579. converse.connection.addHandler(
  2580. $.proxy(function (message) {
  2581. this.onInvite(message);
  2582. return true;
  2583. }, this), 'jabber:x:conference', 'message');
  2584. },
  2585. onConnected: function () {
  2586. this.browserStorage = new Backbone.BrowserStorage[converse.storage](
  2587. b64_sha1('converse.chatboxes-'+converse.bare_jid));
  2588. this.registerMessageHandler();
  2589. this.fetch({
  2590. add: true,
  2591. success: $.proxy(function (collection, resp) {
  2592. if (!_.include(_.pluck(resp, 'id'), 'controlbox')) {
  2593. this.add({
  2594. id: 'controlbox',
  2595. box_id: 'controlbox'
  2596. });
  2597. }
  2598. this.get('controlbox').save({connected:true});
  2599. }, this)
  2600. });
  2601. },
  2602. isOnlyChatStateNotification: function ($msg) {
  2603. // See XEP-0085 Chat State Notification
  2604. return (
  2605. $msg.find('body').length === 0 && (
  2606. $msg.find(ACTIVE).length !== 0 ||
  2607. $msg.find(COMPOSING).length !== 0 ||
  2608. $msg.find(INACTIVE).length !== 0 ||
  2609. $msg.find(PAUSED).length !== 0 ||
  2610. $msg.find(GONE).length !== 0
  2611. )
  2612. );
  2613. },
  2614. onInvite: function (message) {
  2615. var $message = $(message),
  2616. $x = $message.children('x[xmlns="jabber:x:conference"]'),
  2617. from = Strophe.getBareJidFromJid($message.attr('from')),
  2618. room_jid = $x.attr('jid'),
  2619. reason = $x.attr('reason'),
  2620. contact = converse.roster.get(from),
  2621. result;
  2622. if (!reason) {
  2623. result = confirm(
  2624. __(___("%1$s has invited you to join a chat room: %2$s"), contact.get('fullname'), room_jid)
  2625. );
  2626. } else {
  2627. result = confirm(
  2628. __(___('%1$s has invited you to join a chat room: %2$s, and left the following reason: "%3$s"'),
  2629. contact.get('fullname'), room_jid, reason)
  2630. );
  2631. }
  2632. if (result === true) {
  2633. var chatroom = converse.chatboxviews.showChat({
  2634. 'id': room_jid,
  2635. 'jid': room_jid,
  2636. 'name': Strophe.unescapeNode(Strophe.getNodeFromJid(room_jid)),
  2637. 'nick': Strophe.unescapeNode(Strophe.getNodeFromJid(converse.connection.jid)),
  2638. 'chatroom': true,
  2639. 'box_id' : b64_sha1(room_jid),
  2640. 'password': $x.attr('password')
  2641. });
  2642. if (!chatroom.get('connected')) {
  2643. converse.chatboxviews.get(room_jid).connect(null);
  2644. }
  2645. }
  2646. },
  2647. onMessage: function (message) {
  2648. var $message = $(message);
  2649. var buddy_jid, $forwarded, $received,
  2650. message_from = $message.attr('from');
  2651. if (message_from === converse.connection.jid) {
  2652. // FIXME: Forwarded messages should be sent to specific resources,
  2653. // not broadcasted
  2654. return true;
  2655. }
  2656. $forwarded = $message.children('forwarded');
  2657. $received = $message.children('received[xmlns="urn:xmpp:carbons:2"]');
  2658. if ($forwarded.length) {
  2659. $message = $forwarded.children('message');
  2660. } else if ($received.length) {
  2661. $message = $received.children('forwarded').children('message');
  2662. message_from = $message.attr('from');
  2663. }
  2664. var from = Strophe.getBareJidFromJid(message_from),
  2665. to = Strophe.getBareJidFromJid($message.attr('to')),
  2666. resource, chatbox, roster_item;
  2667. if (from == converse.bare_jid) {
  2668. // I am the sender, so this must be a forwarded message...
  2669. buddy_jid = to;
  2670. resource = Strophe.getResourceFromJid($message.attr('to'));
  2671. } else {
  2672. buddy_jid = from;
  2673. resource = Strophe.getResourceFromJid(message_from);
  2674. }
  2675. chatbox = this.get(buddy_jid);
  2676. roster_item = converse.roster.get(buddy_jid);
  2677. if (roster_item === undefined) {
  2678. // The buddy was likely removed
  2679. converse.log('Could not get roster item for JID '+buddy_jid, 'error');
  2680. return true;
  2681. }
  2682. if (!chatbox) {
  2683. var fullname = roster_item.get('fullname');
  2684. fullname = _.isEmpty(fullname)? buddy_jid: fullname;
  2685. chatbox = this.create({
  2686. 'id': buddy_jid,
  2687. 'jid': buddy_jid,
  2688. 'fullname': fullname,
  2689. 'image_type': roster_item.get('image_type'),
  2690. 'image': roster_item.get('image'),
  2691. 'url': roster_item.get('url')
  2692. });
  2693. }
  2694. if (!this.isOnlyChatStateNotification($message) && from !== converse.bare_jid) {
  2695. playNotification();
  2696. }
  2697. chatbox.receiveMessage($message);
  2698. converse.roster.addResource(buddy_jid, resource);
  2699. converse.emit('message', message);
  2700. return true;
  2701. }
  2702. });
  2703. this.ChatBoxViews = Backbone.Overview.extend({
  2704. initialize: function () {
  2705. this.model.on("add", this.onChatBoxAdded, this);
  2706. this.model.on("change:minimized", function (item) {
  2707. if (item.get('minimized') === false) {
  2708. this.trimChats(this.get(item.get('id')));
  2709. } else {
  2710. this.trimChats();
  2711. }
  2712. }, this);
  2713. },
  2714. _ensureElement: function() {
  2715. /* Override method from backbone.js
  2716. * If the #conversejs element doesn't exist, create it.
  2717. */
  2718. if (!this.el) {
  2719. var $el = $('#conversejs');
  2720. if (!$el.length) {
  2721. $el = $('<div id="conversejs">');
  2722. $('body').append($el);
  2723. }
  2724. $el.html(converse.templates.chats_panel());
  2725. this.setElement($el, false);
  2726. } else {
  2727. this.setElement(_.result(this, 'el'), false);
  2728. }
  2729. },
  2730. onChatBoxAdded: function (item) {
  2731. var view = this.get(item.get('id'));
  2732. if (!view) {
  2733. if (item.get('chatroom')) {
  2734. view = new converse.ChatRoomView({'model': item});
  2735. } else if (item.get('box_id') === 'controlbox') {
  2736. view = new converse.ControlBoxView({model: item});
  2737. } else {
  2738. view = new converse.ChatBoxView({model: item});
  2739. }
  2740. this.add(item.get('id'), view);
  2741. } else {
  2742. delete view.model; // Remove ref to old model to help garbage collection
  2743. view.model = item;
  2744. view.initialize();
  2745. }
  2746. this.trimChats(view);
  2747. },
  2748. trimChats: function (newchat) {
  2749. /* This method is called when a newly created chat box will
  2750. * be shown.
  2751. *
  2752. * It checks whether there is enough space on the page to show
  2753. * another chat box. Otherwise it minimize the oldest chat box
  2754. * to create space.
  2755. */
  2756. if (converse.no_trimming || (this.model.length <= 1)) {
  2757. return;
  2758. }
  2759. var oldest_chat,
  2760. controlbox_width = 0,
  2761. $minimized = converse.minimized_chats.$el,
  2762. minimized_width = _.contains(this.model.pluck('minimized'), true) ? $minimized.outerWidth(true) : 0,
  2763. boxes_width = newchat ? newchat.$el.outerWidth(true) : 0,
  2764. new_id = newchat ? newchat.model.get('id') : null,
  2765. controlbox = this.get('controlbox');
  2766. if (!controlbox || !controlbox.$el.is(':visible')) {
  2767. controlbox_width = converse.controlboxtoggle.$el.outerWidth(true);
  2768. } else {
  2769. controlbox_width = controlbox.$el.outerWidth(true);
  2770. }
  2771. _.each(this.getAll(), function (view) {
  2772. var id = view.model.get('id');
  2773. if ((id !== 'controlbox') && (id !== new_id) && (!view.model.get('minimized')) && view.$el.is(':visible')) {
  2774. boxes_width += view.$el.outerWidth(true);
  2775. }
  2776. });
  2777. if ((minimized_width + boxes_width + controlbox_width) > this.$el.outerWidth(true)) {
  2778. oldest_chat = this.getOldestMaximizedChat();
  2779. if (oldest_chat) {
  2780. oldest_chat.minimize();
  2781. }
  2782. }
  2783. },
  2784. getOldestMaximizedChat: function () {
  2785. // Get oldest view (which is not controlbox)
  2786. var i = 0;
  2787. var model = this.model.sort().at(i);
  2788. while (model.get('id') === 'controlbox' || model.get('minimized') === true) {
  2789. i++;
  2790. model = this.model.at(i);
  2791. if (!model) {
  2792. return null;
  2793. }
  2794. }
  2795. return model;
  2796. },
  2797. closeAllChatBoxes: function (include_controlbox) {
  2798. var i, chatbox;
  2799. // TODO: once Backbone.Overview has been refactored, we should
  2800. // be able to call .each on the views themselves.
  2801. this.model.each($.proxy(function (model) {
  2802. var id = model.get('id');
  2803. if (include_controlbox || id !== 'controlbox') {
  2804. this.get(id).close();
  2805. }
  2806. }, this));
  2807. return this;
  2808. },
  2809. showChat: function (attrs) {
  2810. /* Find the chat box and show it.
  2811. * If it doesn't exist, create it.
  2812. */
  2813. var chatbox = this.model.get(attrs.jid);
  2814. if (chatbox) {
  2815. if (chatbox.get('minimized')) {
  2816. chatbox.maximize();
  2817. } else {
  2818. chatbox.trigger('show');
  2819. }
  2820. } else {
  2821. chatbox = this.model.create(attrs, {
  2822. 'error': function (model, response) {
  2823. converse.log(response.responseText);
  2824. }
  2825. });
  2826. }
  2827. return chatbox;
  2828. }
  2829. });
  2830. this.MinimizedChatBoxView = Backbone.View.extend({
  2831. tagName: 'div',
  2832. className: 'chat-head',
  2833. events: {
  2834. 'click .close-chatbox-button': 'close',
  2835. 'click .restore-chat': 'restore'
  2836. },
  2837. initialize: function () {
  2838. this.model.messages.on('add', this.updateUnreadMessagesCounter, this);
  2839. this.model.on('showSentOTRMessage', this.updateUnreadMessagesCounter, this);
  2840. this.model.on('showReceivedOTRMessage', this.updateUnreadMessagesCounter, this);
  2841. this.model.on('change:minimized', this.clearUnreadMessagesCounter, this);
  2842. },
  2843. render: function () {
  2844. var data = _.extend(
  2845. this.model.toJSON(),
  2846. { 'tooltip': __('Click to restore this chat') }
  2847. );
  2848. if (this.model.get('chatroom')) {
  2849. data.title = this.model.get('name');
  2850. this.$el.addClass('chat-head-chatroom');
  2851. } else {
  2852. data.title = this.model.get('fullname');
  2853. this.$el.addClass('chat-head-chatbox');
  2854. }
  2855. return this.$el.html(converse.templates.trimmed_chat(data));
  2856. },
  2857. clearUnreadMessagesCounter: function () {
  2858. this.model.set({'num_unread': 0});
  2859. this.render();
  2860. },
  2861. updateUnreadMessagesCounter: function () {
  2862. this.model.set({'num_unread': this.model.get('num_unread') + 1});
  2863. this.render();
  2864. },
  2865. close: function (ev) {
  2866. if (ev && ev.preventDefault) { ev.preventDefault(); }
  2867. this.remove();
  2868. this.model.destroy();
  2869. converse.emit('chatBoxClosed', this);
  2870. return this;
  2871. },
  2872. restore: function(ev) {
  2873. if (ev && ev.preventDefault) {
  2874. ev.preventDefault();
  2875. }
  2876. this._restore();
  2877. },
  2878. _restore: _.debounce(function () {
  2879. this.remove();
  2880. this.model.maximize();
  2881. }, 200)
  2882. });
  2883. this.MinimizedChats = Backbone.Overview.extend({
  2884. el: "#minimized-chats",
  2885. events: {
  2886. "click #toggle-minimized-chats": "toggle"
  2887. },
  2888. initialize: function () {
  2889. this.initToggle();
  2890. this.model.on("add", this.onChanged, this);
  2891. this.model.on("destroy", this.removeChat, this);
  2892. this.model.on("change:minimized", this.onChanged, this);
  2893. this.model.on('change:num_unread', this.updateUnreadMessagesCounter, this);
  2894. },
  2895. tearDown: function () {
  2896. this.model.off("add", this.onChanged);
  2897. this.model.off("destroy", this.removeChat);
  2898. this.model.off("change:minimized", this.onChanged);
  2899. this.model.off('change:num_unread', this.updateUnreadMessagesCounter);
  2900. return this;
  2901. },
  2902. initToggle: function () {
  2903. this.toggleview = new converse.MinimizedChatsToggleView({
  2904. model: new converse.MinimizedChatsToggle()
  2905. });
  2906. var id = b64_sha1('converse.minchatstoggle'+converse.bare_jid);
  2907. this.toggleview.model.id = id; // Appears to be necessary for backbone.browserStorage
  2908. this.toggleview.model.browserStorage = new Backbone.BrowserStorage[converse.storage](id);
  2909. this.toggleview.model.fetch();
  2910. },
  2911. render: function () {
  2912. if (this.keys().length === 0) {
  2913. this.$el.hide('fast');
  2914. } else if (this.keys().length === 1) {
  2915. this.$el.show('fast');
  2916. }
  2917. return this.$el;
  2918. },
  2919. toggle: function (ev) {
  2920. if (ev && ev.preventDefault) { ev.preventDefault(); }
  2921. this.toggleview.model.save({'collapsed': !this.toggleview.model.get('collapsed')});
  2922. this.$('.minimized-chats-flyout').toggle();
  2923. },
  2924. onChanged: function (item) {
  2925. if (item.get('id') !== 'controlbox' && item.get('minimized')) {
  2926. this.addChat(item);
  2927. } else if (this.get(item.get('id'))) {
  2928. this.removeChat(item);
  2929. }
  2930. },
  2931. addChat: function (item) {
  2932. var existing = this.get(item.get('id'));
  2933. if (existing && existing.$el.parent().length !== 0) {
  2934. return;
  2935. }
  2936. var view = new converse.MinimizedChatBoxView({model: item});
  2937. this.$('.minimized-chats-flyout').append(view.render());
  2938. this.add(item.get('id'), view);
  2939. this.toggleview.model.set({'num_minimized': this.keys().length});
  2940. this.render();
  2941. },
  2942. removeChat: function (item) {
  2943. this.remove(item.get('id'));
  2944. this.toggleview.model.set({'num_minimized': this.keys().length});
  2945. this.render();
  2946. },
  2947. updateUnreadMessagesCounter: function () {
  2948. var ls = this.model.pluck('num_unread'),
  2949. count = 0, i;
  2950. for (i=0; i<ls.length; i++) { count += ls[i]; }
  2951. this.toggleview.model.set({'num_unread': count});
  2952. this.render();
  2953. }
  2954. });
  2955. this.MinimizedChatsToggle = Backbone.Model.extend({
  2956. initialize: function () {
  2957. this.set({
  2958. 'collapsed': this.get('collapsed') || false,
  2959. 'num_minimized': this.get('num_minimized') || 0,
  2960. 'num_unread': this.get('num_unread') || 0,
  2961. });
  2962. }
  2963. });
  2964. this.MinimizedChatsToggleView = Backbone.View.extend({
  2965. el: '#toggle-minimized-chats',
  2966. initialize: function () {
  2967. this.model.on('change:num_minimized', this.render, this);
  2968. this.model.on('change:num_unread', this.render, this);
  2969. this.$flyout = this.$el.siblings('.minimized-chats-flyout');
  2970. },
  2971. render: function () {
  2972. this.$el.html(converse.templates.toggle_chats(
  2973. _.extend(this.model.toJSON(), {
  2974. 'Minimized': __('Minimized')
  2975. })
  2976. ));
  2977. if (this.model.get('collapsed')) {
  2978. this.$flyout.hide();
  2979. } else {
  2980. this.$flyout.show();
  2981. }
  2982. return this.$el;
  2983. },
  2984. });
  2985. this.RosterContact = Backbone.Model.extend({
  2986. initialize: function (attributes, options) {
  2987. var jid = attributes.jid;
  2988. var attrs = _.extend({
  2989. 'id': jid,
  2990. 'fullname': jid,
  2991. 'chat_status': 'offline',
  2992. 'user_id': Strophe.getNodeFromJid(jid),
  2993. 'resources': [],
  2994. 'groups': [],
  2995. 'status': ''
  2996. }, attributes);
  2997. this.set(attrs);
  2998. }
  2999. });
  3000. this.RosterContactView = Backbone.View.extend({
  3001. tagName: 'dd',
  3002. events: {
  3003. "click .accept-xmpp-request": "acceptRequest",
  3004. "click .decline-xmpp-request": "declineRequest",
  3005. "click .open-chat": "openChat",
  3006. "click .remove-xmpp-contact": "removeContact"
  3007. },
  3008. initialize: function () {
  3009. this.model.on("change", this.onChange, this);
  3010. this.model.on("remove", this.remove, this);
  3011. this.model.on("destroy", this.remove, this);
  3012. this.model.on("open", this.openChat, this);
  3013. },
  3014. onChange: function () {
  3015. if (converse.show_only_online_users) {
  3016. if (this.model.get('chat_status') !== 'online') {
  3017. this.$el.hide();
  3018. } else {
  3019. this.$el.show();
  3020. }
  3021. } else {
  3022. this.render();
  3023. }
  3024. },
  3025. openChat: function (ev) {
  3026. if (ev && ev.preventDefault) { ev.preventDefault(); }
  3027. return converse.chatboxviews.showChat({
  3028. 'id': this.model.get('jid'),
  3029. 'jid': this.model.get('jid'),
  3030. 'fullname': this.model.get('fullname'),
  3031. 'image_type': this.model.get('image_type'),
  3032. 'image': this.model.get('image'),
  3033. 'url': this.model.get('url'),
  3034. 'status': this.model.get('status')
  3035. });
  3036. },
  3037. removeContact: function (ev) {
  3038. if (ev && ev.preventDefault) { ev.preventDefault(); }
  3039. var result = confirm(__("Are you sure you want to remove this contact?"));
  3040. if (result === true) {
  3041. var bare_jid = this.model.get('jid');
  3042. converse.connection.roster.remove(bare_jid, $.proxy(function (iq) {
  3043. converse.connection.roster.unauthorize(bare_jid);
  3044. converse.rosterview.model.remove(bare_jid);
  3045. this.model.destroy();
  3046. this.remove();
  3047. }, this));
  3048. }
  3049. },
  3050. acceptRequest: function (ev) {
  3051. if (ev && ev.preventDefault) { ev.preventDefault(); }
  3052. var jid = this.model.get('jid');
  3053. converse.connection.roster.authorize(jid);
  3054. converse.connection.roster.add(jid, this.model.get('fullname'), [], function (iq) {
  3055. converse.connection.roster.subscribe(jid, null, converse.xmppstatus.get('fullname'));
  3056. });
  3057. },
  3058. declineRequest: function (ev) {
  3059. if (ev && ev.preventDefault) { ev.preventDefault(); }
  3060. var result = confirm(__("Are you sure you want to decline this contact request?"));
  3061. if (result === true) {
  3062. converse.connection.roster.unauthorize(this.model.get('jid'));
  3063. this.model.destroy();
  3064. }
  3065. return this;
  3066. },
  3067. render: function () {
  3068. var item = this.model,
  3069. ask = item.get('ask'),
  3070. chat_status = item.get('chat_status'),
  3071. requesting = item.get('requesting'),
  3072. subscription = item.get('subscription');
  3073. var classes_to_remove = [
  3074. 'current-xmpp-contact',
  3075. 'pending-xmpp-contact',
  3076. 'requesting-xmpp-contact'
  3077. ].concat(_.keys(STATUSES));
  3078. _.each(classes_to_remove,
  3079. function (cls) {
  3080. if (this.el.className.indexOf(cls) !== -1) {
  3081. this.$el.removeClass(cls);
  3082. }
  3083. }, this);
  3084. this.$el.addClass(chat_status).data('status', chat_status);
  3085. if ((ask === 'subscribe') || (subscription === 'from')) {
  3086. /* ask === 'subscribe'
  3087. * Means we have asked to subscribe to them.
  3088. *
  3089. * subscription === 'from'
  3090. * They are subscribed to use, but not vice versa.
  3091. * We assume that there is a pending subscription
  3092. * from us to them (otherwise we're in a state not
  3093. * supported by converse.js).
  3094. *
  3095. * So in both cases the user is a "pending" contact.
  3096. */
  3097. this.$el.addClass('pending-xmpp-contact');
  3098. this.$el.html(converse.templates.pending_contact(
  3099. _.extend(item.toJSON(), {
  3100. 'desc_remove': __('Click to remove this contact')
  3101. })
  3102. ));
  3103. } else if (requesting === true) {
  3104. this.$el.addClass('requesting-xmpp-contact');
  3105. this.$el.html(converse.templates.requesting_contact(
  3106. _.extend(item.toJSON(), {
  3107. 'desc_accept': __("Click to accept this contact request"),
  3108. 'desc_decline': __("Click to decline this contact request"),
  3109. })
  3110. ));
  3111. converse.controlboxtoggle.showControlBox();
  3112. } else if (subscription === 'both' || subscription === 'to') {
  3113. this.$el.addClass('current-xmpp-contact');
  3114. this.$el.html(converse.templates.roster_item(
  3115. _.extend(item.toJSON(), {
  3116. 'desc_status': STATUSES[chat_status||'offline'],
  3117. 'desc_chat': __('Click to chat with this contact'),
  3118. 'desc_remove': __('Click to remove this contact')
  3119. })
  3120. ));
  3121. }
  3122. return this;
  3123. }
  3124. });
  3125. this.RosterContacts = Backbone.Collection.extend({
  3126. model: converse.RosterContact,
  3127. comparator: function (contact1, contact2) {
  3128. var name1 = contact1.get('fullname').toLowerCase();
  3129. var status1 = contact1.get('chat_status') || 'offline';
  3130. var name2 = contact2.get('fullname').toLowerCase();
  3131. var status2 = contact2.get('chat_status') || 'offline';
  3132. if (STATUS_WEIGHTS[status1] === STATUS_WEIGHTS[status2]) {
  3133. return name1 < name2 ? -1 : (name1 > name2? 1 : 0);
  3134. } else {
  3135. return STATUS_WEIGHTS[status1] < STATUS_WEIGHTS[status2] ? -1 : 1;
  3136. }
  3137. },
  3138. subscribeToSuggestedItems: function (msg) {
  3139. $(msg).find('item').each(function () {
  3140. var $this = $(this),
  3141. jid = $this.attr('jid'),
  3142. action = $this.attr('action'),
  3143. fullname = $this.attr('name');
  3144. if (action === 'add') {
  3145. converse.connection.roster.add(jid, fullname, [], function (iq) {
  3146. converse.connection.roster.subscribe(jid, null, converse.xmppstatus.get('fullname'));
  3147. });
  3148. }
  3149. });
  3150. return true;
  3151. },
  3152. isSelf: function (jid) {
  3153. return (Strophe.getBareJidFromJid(jid) === Strophe.getBareJidFromJid(converse.connection.jid));
  3154. },
  3155. addResource: function (bare_jid, resource) {
  3156. var item = this.get(bare_jid),
  3157. resources;
  3158. if (item) {
  3159. resources = item.get('resources');
  3160. if (resources) {
  3161. if (_.indexOf(resources, resource) == -1) {
  3162. resources.push(resource);
  3163. item.set({'resources': resources});
  3164. }
  3165. } else {
  3166. item.set({'resources': [resource]});
  3167. }
  3168. }
  3169. },
  3170. removeResource: function (bare_jid, resource) {
  3171. var item = this.get(bare_jid),
  3172. resources,
  3173. idx;
  3174. if (item) {
  3175. resources = item.get('resources');
  3176. idx = _.indexOf(resources, resource);
  3177. if (idx !== -1) {
  3178. resources.splice(idx, 1);
  3179. item.set({'resources': resources});
  3180. return resources.length;
  3181. }
  3182. }
  3183. return 0;
  3184. },
  3185. subscribeBack: function (jid) {
  3186. var bare_jid = Strophe.getBareJidFromJid(jid);
  3187. if (converse.connection.roster.findItem(bare_jid)) {
  3188. converse.connection.roster.authorize(bare_jid);
  3189. converse.connection.roster.subscribe(jid, null, converse.xmppstatus.get('fullname'));
  3190. } else {
  3191. converse.connection.roster.add(jid, '', [], function (iq) {
  3192. converse.connection.roster.authorize(bare_jid);
  3193. converse.connection.roster.subscribe(jid, null, converse.xmppstatus.get('fullname'));
  3194. });
  3195. }
  3196. },
  3197. unsubscribe: function (jid) {
  3198. /* Upon receiving the presence stanza of type "unsubscribed",
  3199. * the user SHOULD acknowledge receipt of that subscription state
  3200. * notification by sending a presence stanza of type "unsubscribe"
  3201. * this step lets the user's server know that it MUST no longer
  3202. * send notification of the subscription state change to the user.
  3203. */
  3204. converse.xmppstatus.sendPresence('unsubscribe');
  3205. if (converse.connection.roster.findItem(jid)) {
  3206. converse.connection.roster.remove(jid, function (iq) {
  3207. converse.rosterview.model.remove(jid);
  3208. });
  3209. }
  3210. },
  3211. getNumOnlineContacts: function () {
  3212. var count = 0,
  3213. ignored = ['offline', 'unavailable'],
  3214. models = this.models,
  3215. models_length = models.length,
  3216. i;
  3217. if (converse.show_only_online_users) {
  3218. ignored = _.union(ignored, ['dnd', 'xa', 'away']);
  3219. }
  3220. for (i=0; i<models_length; i++) {
  3221. if (_.indexOf(ignored, models[i].get('chat_status')) === -1) {
  3222. count++;
  3223. }
  3224. }
  3225. return count;
  3226. },
  3227. clearCache: function (items) {
  3228. /* The localstorage cache containing roster contacts might contain
  3229. * some contacts that aren't actually in our roster anymore. We
  3230. * therefore need to remove them now.
  3231. */
  3232. var id, i, contact;
  3233. for (i=0; i < this.models.length; ++i) {
  3234. id = this.models[i].get('id');
  3235. if (_.indexOf(_.pluck(items, 'jid'), id) === -1) {
  3236. contact = this.get(id);
  3237. if (contact) {
  3238. contact.destroy();
  3239. }
  3240. }
  3241. }
  3242. },
  3243. rosterHandler: function (items) {
  3244. converse.emit('roster', items);
  3245. this.clearCache(items);
  3246. _.each(items, function (item, index, items) {
  3247. if (this.isSelf(item.jid)) { return; }
  3248. var model = this.get(item.jid);
  3249. if (!model) {
  3250. var is_last = (index === (items.length-1)) ? true : false;
  3251. if ((item.subscription === 'none') && (item.ask === null) && !is_last) {
  3252. // We're not interested in zombies
  3253. // (Hack: except if it's the last item, then we still
  3254. // add it so that the roster will be shown).
  3255. return;
  3256. }
  3257. this.create({
  3258. ask: item.ask,
  3259. fullname: item.name || item.jid,
  3260. groups: item.groups,
  3261. jid: item.jid,
  3262. subscription: item.subscription
  3263. });
  3264. } else {
  3265. if ((item.subscription === 'none') && (item.ask === null)) {
  3266. // This user is no longer in our roster
  3267. model.destroy();
  3268. } else {
  3269. // We only find out about requesting contacts via the
  3270. // presence handler, so if we receive a contact
  3271. // here, we know they aren't requesting anymore.
  3272. // see docs/DEVELOPER.rst
  3273. model.save({
  3274. subscription: item.subscription,
  3275. ask: item.ask,
  3276. requesting: null,
  3277. groups: item.groups
  3278. });
  3279. }
  3280. }
  3281. }, this);
  3282. if (!converse.initial_presence_sent) {
  3283. /* Once we've sent out our initial presence stanza, we'll
  3284. * start receiving presence stanzas from our contacts.
  3285. * We therefore only want to do this after our roster has
  3286. * been set up (otherwise we can't meaningfully process
  3287. * incoming presence stanzas).
  3288. */
  3289. converse.initial_presence_sent = 1;
  3290. converse.xmppstatus.sendPresence();
  3291. }
  3292. },
  3293. handleIncomingSubscription: function (jid) {
  3294. var bare_jid = Strophe.getBareJidFromJid(jid);
  3295. var item = this.get(bare_jid);
  3296. if (!converse.allow_contact_requests) {
  3297. converse.connection.roster.unauthorize(bare_jid);
  3298. return true;
  3299. }
  3300. if (converse.auto_subscribe) {
  3301. if ((!item) || (item.get('subscription') != 'to')) {
  3302. this.subscribeBack(jid);
  3303. } else {
  3304. converse.connection.roster.authorize(bare_jid);
  3305. }
  3306. } else {
  3307. if ((item) && (item.get('subscription') != 'none')) {
  3308. converse.connection.roster.authorize(bare_jid);
  3309. } else {
  3310. if (!this.get(bare_jid)) {
  3311. converse.getVCard(
  3312. bare_jid,
  3313. $.proxy(function (jid, fullname, img, img_type, url) {
  3314. this.add({
  3315. jid: bare_jid,
  3316. subscription: 'none',
  3317. ask: null,
  3318. requesting: true,
  3319. fullname: fullname || jid,
  3320. image: img,
  3321. image_type: img_type,
  3322. url: url,
  3323. vcard_updated: moment().format()
  3324. });
  3325. }, this),
  3326. $.proxy(function (jid, iq) {
  3327. converse.log("Error while retrieving vcard");
  3328. this.add({
  3329. jid: bare_jid,
  3330. subscription: 'none',
  3331. ask: null,
  3332. requesting: true,
  3333. fullname: bare_jid,
  3334. vcard_updated: moment().format()
  3335. });
  3336. }, this)
  3337. );
  3338. } else {
  3339. return true;
  3340. }
  3341. }
  3342. }
  3343. return true;
  3344. },
  3345. presenceHandler: function (presence) {
  3346. var $presence = $(presence),
  3347. presence_type = $presence.attr('type');
  3348. if (presence_type === 'error') {
  3349. return true;
  3350. }
  3351. var jid = $presence.attr('from'),
  3352. bare_jid = Strophe.getBareJidFromJid(jid),
  3353. resource = Strophe.getResourceFromJid(jid),
  3354. $show = $presence.find('show'),
  3355. chat_status = $show.text() || 'online',
  3356. status_message = $presence.find('status'),
  3357. contact;
  3358. if (this.isSelf(bare_jid)) {
  3359. if ((converse.connection.jid !== jid)&&(presence_type !== 'unavailable')) {
  3360. // Another resource has changed it's status, we'll update ours as well.
  3361. converse.xmppstatus.save({'status': chat_status});
  3362. }
  3363. return true;
  3364. } else if (($presence.find('x').attr('xmlns') || '').indexOf(Strophe.NS.MUC) === 0) {
  3365. return true; // Ignore MUC
  3366. }
  3367. contact = this.get(bare_jid);
  3368. if (contact && (status_message.text() != contact.get('status'))) {
  3369. contact.save({'status': status_message.text()});
  3370. }
  3371. if ((presence_type === 'subscribed') || (presence_type === 'unsubscribe')) {
  3372. return true;
  3373. } else if (presence_type === 'subscribe') {
  3374. return this.handleIncomingSubscription(jid);
  3375. } else if (presence_type === 'unsubscribed') {
  3376. this.unsubscribe(bare_jid);
  3377. } else if (presence_type === 'unavailable') {
  3378. if (this.removeResource(bare_jid, resource) === 0) {
  3379. if (contact) {
  3380. contact.save({'chat_status': 'offline'});
  3381. }
  3382. }
  3383. } else if (contact) {
  3384. // presence_type is undefined
  3385. this.addResource(bare_jid, resource);
  3386. contact.save({'chat_status': chat_status});
  3387. }
  3388. return true;
  3389. }
  3390. });
  3391. this.RosterGroup = Backbone.Model.extend({
  3392. initialize: function (attributes, options) {
  3393. this.set(_.extend({
  3394. description: DESC_GROUP_TOGGLE,
  3395. state: OPENED
  3396. }, attributes));
  3397. // Collection of contacts belonging to this group.
  3398. this.contacts = new converse.RosterContacts();
  3399. }
  3400. });
  3401. this.RosterGroupView = Backbone.Overview.extend({
  3402. tagName: 'dt',
  3403. className: 'roster-group',
  3404. events: {
  3405. "click a.group-toggle": "toggle"
  3406. },
  3407. initialize: function () {
  3408. this.model.contacts.on("add", this.addContact, this);
  3409. this.model.contacts.on("change:subscription", this.onContactSubscriptionChange, this);
  3410. this.model.contacts.on("change:requesting", this.onContactRequestChange, this);
  3411. this.model.contacts.on("change:chat_status", function (contact) {
  3412. // This might be optimized by instead of first sorting,
  3413. // finding the correct position in positionContact
  3414. this.model.contacts.sort();
  3415. this.positionContact(contact).render();
  3416. }, this);
  3417. this.model.contacts.on("destroy", this.onRemove, this);
  3418. this.model.contacts.on("remove", this.onRemove, this);
  3419. converse.roster.on('change:groups', this.onContactGroupChange, this);
  3420. },
  3421. render: function () {
  3422. this.$el.attr('data-group', this.model.get('name'));
  3423. this.$el.html(
  3424. $(converse.templates.group_header({
  3425. label_group: this.model.get('name'),
  3426. desc_group_toggle: this.model.get('description'),
  3427. toggle_state: this.model.get('state')
  3428. }))
  3429. );
  3430. return this;
  3431. },
  3432. addContact: function (contact) {
  3433. var view = new converse.RosterContactView({model: contact});
  3434. this.add(contact.get('id'), view);
  3435. view = this.positionContact(contact).render();
  3436. if (this.model.get('state') === CLOSED) {
  3437. view.$el.hide();
  3438. this.$el.show();
  3439. } else {
  3440. this.show();
  3441. }
  3442. },
  3443. positionContact: function (contact) {
  3444. /* Place the contact's DOM element in the correct alphabetical
  3445. * position amongst the other contacts in this group.
  3446. */
  3447. var view = this.get(contact.get('id'));
  3448. var index = this.model.contacts.indexOf(contact);
  3449. view.$el.detach();
  3450. if (index === 0) {
  3451. this.$el.after(view.$el);
  3452. } else if (index == (this.model.contacts.length-1)) {
  3453. this.$el.nextUntil('dt').last().after(view.$el);
  3454. } else {
  3455. this.$el.nextUntil('dt').eq(index).before(view.$el);
  3456. }
  3457. return view;
  3458. },
  3459. show: function () {
  3460. this.$el.nextUntil('dt').addBack().show();
  3461. },
  3462. hide: function () {
  3463. this.$el.nextUntil('dt').addBack().hide();
  3464. },
  3465. filter: function (q) {
  3466. /* Filter the group's contacts based on the query "q".
  3467. * The query is matched against the contact's full name.
  3468. * If all contacts are filtered out (i.e. hidden), then the
  3469. * group must be filtered out as well.
  3470. */
  3471. var matches, rejects;
  3472. if (q.length === 0) {
  3473. if (this.model.get('state') === OPENED) {
  3474. this.model.contacts.each($.proxy(function (item) {
  3475. if (!(converse.show_only_online_users && item.get('chat_status') === 'online')) {
  3476. this.get(item.get('id')).$el.show();
  3477. }
  3478. }, this));
  3479. }
  3480. this.showIfInvisible();
  3481. } else {
  3482. q = q.toLowerCase();
  3483. matches = this.model.contacts.filter(contains.not('fullname', q));
  3484. if (matches.length === this.model.contacts.length) { // hide the whole group
  3485. this.hide();
  3486. } else {
  3487. _.each(matches, $.proxy(function (item) {
  3488. this.get(item.get('id')).$el.hide();
  3489. }, this));
  3490. _.each(this.model.contacts.reject(contains.not('fullname', q)), $.proxy(function (item) {
  3491. this.get(item.get('id')).$el.show();
  3492. }, this));
  3493. this.showIfInvisible();
  3494. }
  3495. }
  3496. },
  3497. showIfInvisible: function () {
  3498. if (!this.$el.is(':visible')) {
  3499. this.$el.show();
  3500. }
  3501. },
  3502. toggle: function (ev) {
  3503. if (ev && ev.preventDefault) { ev.preventDefault(); }
  3504. var $el = $(ev.target);
  3505. if ($el.hasClass("icon-opened")) {
  3506. this.$el.nextUntil('dt').slideUp();
  3507. this.model.save({state: CLOSED});
  3508. $el.removeClass("icon-opened").addClass("icon-closed");
  3509. } else {
  3510. $el.removeClass("icon-closed").addClass("icon-opened");
  3511. this.model.save({state: OPENED});
  3512. this.filter(
  3513. converse.rosterview.$('.roster-filter').val(),
  3514. converse.rosterview.$('.filter-type').val()
  3515. );
  3516. }
  3517. },
  3518. onContactGroupChange: function (contact) {
  3519. var in_this_group = _.contains(contact.get('groups'), this.model.get('name'));
  3520. var cid = contact.get('id');
  3521. var in_this_overview = !this.get(cid);
  3522. if (in_this_group && !in_this_overview) {
  3523. this.model.contacts.remove(cid);
  3524. } else if (!in_this_group && in_this_overview) {
  3525. this.addContact(contact);
  3526. }
  3527. },
  3528. onContactSubscriptionChange: function (contact) {
  3529. if ((this.model.get('name') === HEADER_PENDING_CONTACTS) && contact.get('subscription') !== 'from') {
  3530. this.model.contacts.remove(contact.get('id'));
  3531. }
  3532. },
  3533. onContactRequestChange: function (contact) {
  3534. if ((this.model.get('name') === HEADER_REQUESTING_CONTACTS) && !contact.get('requesting')) {
  3535. this.model.contacts.remove(contact.get('id'));
  3536. }
  3537. },
  3538. onRemove: function (contact) {
  3539. this.remove(contact.get('id'));
  3540. if (this.model.contacts.length === 0) {
  3541. this.$el.hide();
  3542. }
  3543. }
  3544. });
  3545. this.RosterGroups = Backbone.Collection.extend({
  3546. model: converse.RosterGroup,
  3547. comparator: function (a, b) {
  3548. /* Groups are sorted alphabetically, ignoring case.
  3549. * However, Ungrouped, Requesting Contacts and Pending Contacts
  3550. * appear last and in that order. */
  3551. a = a.get('name');
  3552. b = b.get('name');
  3553. var special_groups = _.keys(HEADER_WEIGHTS);
  3554. var a_is_special = _.contains(special_groups, a);
  3555. var b_is_special = _.contains(special_groups, b);
  3556. if (!a_is_special && !b_is_special ) {
  3557. return a.toLowerCase() < b.toLowerCase() ? -1 : (a.toLowerCase() > b.toLowerCase() ? 1 : 0);
  3558. } else if (a_is_special && b_is_special) {
  3559. return HEADER_WEIGHTS[a] < HEADER_WEIGHTS[b] ? -1 : (HEADER_WEIGHTS[a] > HEADER_WEIGHTS[b] ? 1 : 0);
  3560. } else if (!a_is_special && b_is_special) {
  3561. return (b === HEADER_CURRENT_CONTACTS) ? 1 : -1;
  3562. } else if (a_is_special && !b_is_special) {
  3563. return (a === HEADER_CURRENT_CONTACTS) ? -1 : 1;
  3564. }
  3565. }
  3566. });
  3567. this.RosterView = Backbone.Overview.extend({
  3568. tagName: 'div',
  3569. id: 'converse-roster',
  3570. events: {
  3571. "keydown .roster-filter": "liveFilter",
  3572. "click .onX": "clearFilter",
  3573. "mousemove .x": "togglePointer",
  3574. "change .filter-type": "changeFilterType"
  3575. },
  3576. initialize: function () {
  3577. this.registerRosterHandler();
  3578. this.registerRosterXHandler();
  3579. this.registerPresenceHandler();
  3580. converse.roster.on("add", this.onContactAdd, this);
  3581. converse.roster.on('change', this.onContactChange, this);
  3582. converse.roster.on("destroy", this.update, this);
  3583. converse.roster.on("remove", this.update, this);
  3584. this.model.on("add", this.onGroupAdd, this);
  3585. this.model.on("reset", this.reset, this);
  3586. },
  3587. update: function () {
  3588. var $count = $('#online-count');
  3589. $count.text('('+converse.roster.getNumOnlineContacts()+')');
  3590. if (!$count.is(':visible')) {
  3591. $count.show();
  3592. }
  3593. return this.showHideFilter();
  3594. },
  3595. render: function () {
  3596. this.$el.html(converse.templates.roster({
  3597. placeholder: __('Type to filter'),
  3598. label_contacts: LABEL_CONTACTS,
  3599. label_groups: LABEL_GROUPS
  3600. }));
  3601. return this;
  3602. },
  3603. fetch: function () {
  3604. this.model.fetch({
  3605. silent: true,
  3606. success: $.proxy(this.positionFetchedGroups, this)
  3607. });
  3608. converse.roster.fetch({add: true});
  3609. return this;
  3610. },
  3611. changeFilterType: function (ev) {
  3612. if (ev && ev.preventDefault) { ev.preventDefault(); }
  3613. this.clearFilter();
  3614. this.filter(
  3615. this.$('.roster-filter').val(),
  3616. ev.target.value
  3617. );
  3618. },
  3619. tog: function (v) {
  3620. return v?'addClass':'removeClass';
  3621. },
  3622. togglePointer: function (ev) {
  3623. if (ev && ev.preventDefault) { ev.preventDefault(); }
  3624. var el = ev.target;
  3625. $(el)[this.tog(el.offsetWidth-18 < ev.clientX-el.getBoundingClientRect().left)]('onX');
  3626. },
  3627. filter: function (query, type) {
  3628. var matches;
  3629. query = query.toLowerCase();
  3630. if (type === 'groups') {
  3631. _.each(this.getAll(), function (view, idx) {
  3632. if (view.model.get('name').toLowerCase().indexOf(query.toLowerCase()) === -1) {
  3633. view.hide();
  3634. } else if (view.model.contacts.length > 0) {
  3635. view.show();
  3636. }
  3637. });
  3638. } else {
  3639. _.each(this.getAll(), function (view) {
  3640. view.filter(query, type);
  3641. });
  3642. }
  3643. },
  3644. liveFilter: _.debounce(function (ev) {
  3645. if (ev && ev.preventDefault) { ev.preventDefault(); }
  3646. var q = ev.target.value;
  3647. var t = this.$('.filter-type').val();
  3648. $(ev.target)[this.tog(q)]('x');
  3649. this.filter(q, t);
  3650. }, 300),
  3651. clearFilter: function (ev) {
  3652. if (ev && ev.preventDefault) {
  3653. ev.preventDefault();
  3654. $(ev.target).removeClass('x onX').val('');
  3655. }
  3656. this.filter('');
  3657. },
  3658. showHideFilter: function () {
  3659. if (!this.$el.is(':visible')) {
  3660. return;
  3661. }
  3662. var $filter = this.$('.roster-filter');
  3663. var $type = this.$('.filter-type');
  3664. var visible = $filter.is(':visible');
  3665. if (visible && $filter.val().length > 0) {
  3666. // Don't hide if user is currently filtering.
  3667. return;
  3668. }
  3669. if (this.$('.roster-contacts').hasScrollBar()) {
  3670. if (!visible) {
  3671. $filter.show();
  3672. $type.show();
  3673. }
  3674. } else {
  3675. $filter.hide();
  3676. $type.hide();
  3677. }
  3678. return this;
  3679. },
  3680. reset: function () {
  3681. converse.roster.reset();
  3682. this.removeAll();
  3683. this.render().update();
  3684. return this;
  3685. },
  3686. registerRosterHandler: function () {
  3687. // Register handlers that depend on the roster
  3688. converse.connection.roster.registerCallback(
  3689. $.proxy(converse.roster.rosterHandler, converse.roster),
  3690. null, 'presence', null);
  3691. },
  3692. registerRosterXHandler: function () {
  3693. converse.connection.addHandler(
  3694. $.proxy(converse.roster.subscribeToSuggestedItems, converse.roster),
  3695. 'http://jabber.org/protocol/rosterx', 'message', null);
  3696. },
  3697. registerPresenceHandler: function () {
  3698. converse.connection.addHandler(
  3699. $.proxy(function (presence) {
  3700. converse.roster.presenceHandler(presence);
  3701. return true;
  3702. }, this), null, 'presence', null);
  3703. },
  3704. onGroupAdd: function (group) {
  3705. var view = new converse.RosterGroupView({model: group});
  3706. this.add(group.get('name'), view.render());
  3707. this.positionGroup(view);
  3708. },
  3709. onContactAdd: function (contact) {
  3710. this.addRosterContact(contact).update();
  3711. if (!contact.get('vcard_updated')) {
  3712. // This will update the vcard, which triggers a change
  3713. // request which will rerender the roster contact.
  3714. converse.getVCard(contact.get('jid'));
  3715. }
  3716. },
  3717. onContactChange: function (contact) {
  3718. this.updateChatBox(contact).update();
  3719. if (_.has(contact.changed, 'subscription')) {
  3720. if (contact.changed.subscription == 'from') {
  3721. this.addContactToGroup(contact, HEADER_PENDING_CONTACTS);
  3722. } else if (contact.get('subscription') === 'both') {
  3723. this.addExistingContact(contact);
  3724. }
  3725. }
  3726. if (_.has(contact.changed, 'ask') && contact.changed.ask == 'subscribe') {
  3727. this.addContactToGroup(contact, HEADER_PENDING_CONTACTS);
  3728. }
  3729. if (_.has(contact.changed, 'subscription') && contact.changed.requesting == 'true') {
  3730. this.addContactToGroup(contact, HEADER_REQUESTING_CONTACTS);
  3731. }
  3732. },
  3733. updateChatBox: function (contact) {
  3734. var chatbox = converse.chatboxes.get(contact.get('jid')),
  3735. changes = {};
  3736. if (!chatbox) {
  3737. return this;
  3738. }
  3739. if (_.has(contact.changed, 'chat_status')) {
  3740. changes.chat_status = contact.get('chat_status');
  3741. }
  3742. if (_.has(contact.changed, 'status')) {
  3743. changes.status = contact.get('status');
  3744. }
  3745. chatbox.save(changes);
  3746. return this;
  3747. },
  3748. positionFetchedGroups: function (model, resp, options) {
  3749. /* Instead of throwing an add event for each group
  3750. * fetched, we wait until they're all fetched and then
  3751. * we position them.
  3752. * Works around the problem of positionGroup not
  3753. * working when all groups besides the one being
  3754. * positioned aren't already in inserted into the
  3755. * roster DOM element.
  3756. */
  3757. model.sort();
  3758. model.each($.proxy(function (group, idx) {
  3759. var view = this.get(group.get('name'));
  3760. if (!view) {
  3761. view = new converse.RosterGroupView({model: group});
  3762. this.add(group.get('name'), view.render());
  3763. }
  3764. if (idx === 0) {
  3765. this.$('.roster-contacts').append(view.$el);
  3766. } else {
  3767. this.appendGroup(view);
  3768. }
  3769. }, this));
  3770. },
  3771. positionGroup: function (view) {
  3772. /* Place the group's DOM element in the correct alphabetical
  3773. * position amongst the other groups in the roster.
  3774. */
  3775. var index = this.model.indexOf(view.model);
  3776. if (index === 0) {
  3777. this.$('.roster-contacts').prepend(view.$el);
  3778. } else if (index == (this.model.length-1)) {
  3779. this.appendGroup(view);
  3780. } else {
  3781. $(this.$('.roster-group').eq(index)).before(view.$el);
  3782. }
  3783. return this;
  3784. },
  3785. appendGroup: function (view) {
  3786. /* Add the group at the bottom of the roster
  3787. */
  3788. var $last = this.$('.roster-group').last();
  3789. var $siblings = $last.siblings('dd');
  3790. if ($siblings.length > 0) {
  3791. $siblings.last().after(view.$el);
  3792. } else {
  3793. $last.after(view.$el);
  3794. }
  3795. return this;
  3796. },
  3797. getGroup: function (name) {
  3798. /* Returns the group as specified by name.
  3799. * Creates the group if it doesn't exist.
  3800. */
  3801. var view = this.get(name);
  3802. if (view) {
  3803. return view.model;
  3804. }
  3805. return this.model.create({name: name, id: b64_sha1(name)});
  3806. },
  3807. addContactToGroup: function (contact, name) {
  3808. this.getGroup(name).contacts.add(contact);
  3809. },
  3810. addExistingContact: function (contact) {
  3811. var groups;
  3812. if (converse.roster_groups) {
  3813. groups = contact.get('groups');
  3814. if (groups.length === 0) {
  3815. groups = [HEADER_UNGROUPED];
  3816. }
  3817. } else {
  3818. groups = [HEADER_CURRENT_CONTACTS];
  3819. }
  3820. _.each(groups, $.proxy(function (name) {
  3821. this.addContactToGroup(contact, name);
  3822. }, this));
  3823. },
  3824. addRosterContact: function (contact) {
  3825. if (contact.get('subscription') === 'both' || contact.get('subscription') === 'to') {
  3826. this.addExistingContact(contact);
  3827. } else {
  3828. if ((contact.get('ask') === 'subscribe') || (contact.get('subscription') === 'from')) {
  3829. this.addContactToGroup(contact, HEADER_PENDING_CONTACTS);
  3830. } else if (contact.get('requesting') === true) {
  3831. this.addContactToGroup(contact, HEADER_REQUESTING_CONTACTS);
  3832. }
  3833. }
  3834. return this;
  3835. }
  3836. });
  3837. this.XMPPStatus = Backbone.Model.extend({
  3838. initialize: function () {
  3839. this.set({
  3840. 'status' : this.get('status') || 'online'
  3841. });
  3842. this.on('change', $.proxy(function (item) {
  3843. if (this.get('fullname') === undefined) {
  3844. converse.getVCard(
  3845. null, // No 'to' attr when getting one's own vCard
  3846. $.proxy(function (jid, fullname, image, image_type, url) {
  3847. this.save({'fullname': fullname});
  3848. }, this)
  3849. );
  3850. }
  3851. if (_.has(item.changed, 'status')) {
  3852. converse.emit('statusChanged', this.get('status'));
  3853. }
  3854. if (_.has(item.changed, 'status_message')) {
  3855. converse.emit('statusMessageChanged', this.get('status_message'));
  3856. }
  3857. }, this));
  3858. },
  3859. sendPresence: function (type) {
  3860. if (type === undefined) {
  3861. type = this.get('status') || 'online';
  3862. }
  3863. var status_message = this.get('status_message'),
  3864. presence;
  3865. // Most of these presence types are actually not explicitly sent,
  3866. // but I add all of them here fore reference and future proofing.
  3867. if ((type === 'unavailable') ||
  3868. (type === 'probe') ||
  3869. (type === 'error') ||
  3870. (type === 'unsubscribe') ||
  3871. (type === 'unsubscribed') ||
  3872. (type === 'subscribe') ||
  3873. (type === 'subscribed')) {
  3874. presence = $pres({'type':type});
  3875. } else {
  3876. if (type === 'online') {
  3877. presence = $pres();
  3878. } else {
  3879. presence = $pres().c('show').t(type).up();
  3880. }
  3881. if (status_message) {
  3882. presence.c('status').t(status_message);
  3883. }
  3884. }
  3885. converse.connection.send(presence);
  3886. },
  3887. setStatus: function (value) {
  3888. this.sendPresence(value);
  3889. this.save({'status': value});
  3890. },
  3891. setStatusMessage: function (status_message) {
  3892. converse.connection.send($pres().c('show').t(this.get('status')).up().c('status').t(status_message));
  3893. this.save({'status_message': status_message});
  3894. if (this.xhr_custom_status) {
  3895. $.ajax({
  3896. url: this.xhr_custom_status_url,
  3897. type: 'POST',
  3898. data: {'msg': status_message}
  3899. });
  3900. }
  3901. }
  3902. });
  3903. this.XMPPStatusView = Backbone.View.extend({
  3904. el: "span#xmpp-status-holder",
  3905. events: {
  3906. "click a.choose-xmpp-status": "toggleOptions",
  3907. "click #fancy-xmpp-status-select a.change-xmpp-status-message": "renderStatusChangeForm",
  3908. "submit #set-custom-xmpp-status": "setStatusMessage",
  3909. "click .dropdown dd ul li a": "setStatus"
  3910. },
  3911. initialize: function () {
  3912. this.model.on("change", this.updateStatusUI, this);
  3913. },
  3914. render: function () {
  3915. // Replace the default dropdown with something nicer
  3916. var $select = this.$el.find('select#select-xmpp-status'),
  3917. chat_status = this.model.get('status') || 'offline',
  3918. options = $('option', $select),
  3919. $options_target,
  3920. options_list = [],
  3921. that = this;
  3922. this.$el.html(converse.templates.choose_status());
  3923. this.$el.find('#fancy-xmpp-status-select')
  3924. .html(converse.templates.chat_status({
  3925. 'status_message': this.model.get('status_message') || __("I am %1$s", this.getPrettyStatus(chat_status)),
  3926. 'chat_status': chat_status,
  3927. 'desc_custom_status': __('Click here to write a custom status message'),
  3928. 'desc_change_status': __('Click to change your chat status')
  3929. }));
  3930. // iterate through all the <option> elements and add option values
  3931. options.each(function(){
  3932. options_list.push(converse.templates.status_option({
  3933. 'value': $(this).val(),
  3934. 'text': this.text
  3935. }));
  3936. });
  3937. $options_target = this.$el.find("#target dd ul").hide();
  3938. $options_target.append(options_list.join(''));
  3939. $select.remove();
  3940. return this;
  3941. },
  3942. toggleOptions: function (ev) {
  3943. ev.preventDefault();
  3944. $(ev.target).parent().parent().siblings('dd').find('ul').toggle('fast');
  3945. },
  3946. renderStatusChangeForm: function (ev) {
  3947. ev.preventDefault();
  3948. var status_message = this.model.get('status') || 'offline';
  3949. var input = converse.templates.change_status_message({
  3950. 'status_message': status_message,
  3951. 'label_custom_status': __('Custom status'),
  3952. 'label_save': __('Save')
  3953. });
  3954. this.$el.find('.xmpp-status').replaceWith(input);
  3955. this.$el.find('.custom-xmpp-status').focus().focus();
  3956. },
  3957. setStatusMessage: function (ev) {
  3958. ev.preventDefault();
  3959. var status_message = $(ev.target).find('input').val();
  3960. this.model.setStatusMessage(status_message);
  3961. },
  3962. setStatus: function (ev) {
  3963. ev.preventDefault();
  3964. var $el = $(ev.target),
  3965. value = $el.attr('data-value');
  3966. if (value === 'logout') {
  3967. this.$el.find(".dropdown dd ul").hide();
  3968. converse.logOut();
  3969. } else {
  3970. this.model.setStatus(value);
  3971. this.$el.find(".dropdown dd ul").hide();
  3972. }
  3973. },
  3974. getPrettyStatus: function (stat) {
  3975. var pretty_status;
  3976. if (stat === 'chat') {
  3977. pretty_status = __('online');
  3978. } else if (stat === 'dnd') {
  3979. pretty_status = __('busy');
  3980. } else if (stat === 'xa') {
  3981. pretty_status = __('away for long');
  3982. } else if (stat === 'away') {
  3983. pretty_status = __('away');
  3984. } else {
  3985. pretty_status = __(stat) || __('online');
  3986. }
  3987. return pretty_status;
  3988. },
  3989. updateStatusUI: function (model) {
  3990. if (!(_.has(model.changed, 'status')) && !(_.has(model.changed, 'status_message'))) {
  3991. return;
  3992. }
  3993. var stat = model.get('status');
  3994. // # For translators: the %1$s part gets replaced with the status
  3995. // # Example, I am online
  3996. var status_message = model.get('status_message') || __("I am %1$s", this.getPrettyStatus(stat));
  3997. this.$el.find('#fancy-xmpp-status-select').html(
  3998. converse.templates.chat_status({
  3999. 'chat_status': stat,
  4000. 'status_message': status_message,
  4001. 'desc_custom_status': __('Click here to write a custom status message'),
  4002. 'desc_change_status': __('Click to change your chat status')
  4003. }));
  4004. }
  4005. });
  4006. this.BOSHSession = Backbone.Model;
  4007. this.Feature = Backbone.Model;
  4008. this.Features = Backbone.Collection.extend({
  4009. /* Service Discovery
  4010. * -----------------
  4011. * This collection stores Feature Models, representing features
  4012. * provided by available XMPP entities (e.g. servers)
  4013. * See XEP-0030 for more details: http://xmpp.org/extensions/xep-0030.html
  4014. * All features are shown here: http://xmpp.org/registrar/disco-features.html
  4015. */
  4016. model: converse.Feature,
  4017. initialize: function () {
  4018. this.addClientIdentities().addClientFeatures();
  4019. this.browserStorage = new Backbone.BrowserStorage[converse.storage](
  4020. b64_sha1('converse.features'+converse.bare_jid));
  4021. if (this.browserStorage.records.length === 0) {
  4022. // browserStorage is empty, so we've likely never queried this
  4023. // domain for features yet
  4024. converse.connection.disco.info(converse.domain, null, $.proxy(this.onInfo, this));
  4025. converse.connection.disco.items(converse.domain, null, $.proxy(this.onItems, this));
  4026. } else {
  4027. this.fetch({add:true});
  4028. }
  4029. },
  4030. addClientIdentities: function () {
  4031. /* See http://xmpp.org/registrar/disco-categories.html
  4032. */
  4033. converse.connection.disco.addIdentity('client', 'web', 'Converse.js');
  4034. return this;
  4035. },
  4036. addClientFeatures: function () {
  4037. /* The strophe.disco.js plugin keeps a list of features which
  4038. * it will advertise to any #info queries made to it.
  4039. *
  4040. * See: http://xmpp.org/extensions/xep-0030.html#info
  4041. *
  4042. * TODO: these features need to be added in the relevant
  4043. * feature-providing Models, not here
  4044. */
  4045. converse.connection.disco.addFeature('http://jabber.org/protocol/chatstates'); // Limited support
  4046. converse.connection.disco.addFeature('http://jabber.org/protocol/rosterx'); // Limited support
  4047. converse.connection.disco.addFeature('jabber:x:conference');
  4048. converse.connection.disco.addFeature('urn:xmpp:carbons:2');
  4049. converse.connection.disco.addFeature('vcard-temp');
  4050. converse.connection.disco.addFeature(Strophe.NS.BOSH);
  4051. converse.connection.disco.addFeature(Strophe.NS.DISCO_INFO);
  4052. converse.connection.disco.addFeature(Strophe.NS.MUC);
  4053. return this;
  4054. },
  4055. onItems: function (stanza) {
  4056. $(stanza).find('query item').each($.proxy(function (idx, item) {
  4057. converse.connection.disco.info(
  4058. $(item).attr('jid'),
  4059. null,
  4060. $.proxy(this.onInfo, this));
  4061. }, this));
  4062. },
  4063. onInfo: function (stanza) {
  4064. var $stanza = $(stanza);
  4065. if (($stanza.find('identity[category=server][type=im]').length === 0) &&
  4066. ($stanza.find('identity[category=conference][type=text]').length === 0)) {
  4067. // This isn't an IM server component
  4068. return;
  4069. }
  4070. $stanza.find('feature').each($.proxy(function (idx, feature) {
  4071. this.create({
  4072. 'var': $(feature).attr('var'),
  4073. 'from': $stanza.attr('from')
  4074. });
  4075. }, this));
  4076. }
  4077. });
  4078. this.LoginPanel = Backbone.View.extend({
  4079. tagName: 'div',
  4080. id: "login-dialog",
  4081. events: {
  4082. 'submit form#converse-login': 'authenticate'
  4083. },
  4084. connect: function ($form, jid, password) {
  4085. if ($form) {
  4086. $form.find('input[type=submit]').hide().after('<span class="spinner login-submit"/>');
  4087. }
  4088. var resource = Strophe.getResourceFromJid(jid);
  4089. if (!resource) {
  4090. jid += '/converse.js-' + Math.floor(Math.random()*139749825).toString();
  4091. }
  4092. converse.connection.connect(jid, password, converse.onConnect);
  4093. },
  4094. initialize: function (cfg) {
  4095. cfg.$parent.html(this.$el.html(
  4096. converse.templates.login_panel({
  4097. 'label_username': __('XMPP/Jabber Username:'),
  4098. 'label_password': __('Password:'),
  4099. 'label_login': __('Log In')
  4100. })
  4101. ));
  4102. this.$tabs = cfg.$parent.parent().find('#controlbox-tabs');
  4103. },
  4104. render: function () {
  4105. this.$tabs.append(converse.templates.login_tab({label_sign_in: __('Sign in')}));
  4106. this.$el.find('input#jid').focus();
  4107. return this;
  4108. },
  4109. authenticate: function (ev) {
  4110. if (ev && ev.preventDefault) { ev.preventDefault(); }
  4111. var $form = $(ev.target),
  4112. $jid_input = $form.find('input[name=jid]'),
  4113. jid = $jid_input.val(),
  4114. $pw_input = $form.find('input[name=password]'),
  4115. password = $pw_input.val(),
  4116. $bsu_input = null,
  4117. errors = false;
  4118. if (! converse.bosh_service_url) {
  4119. $bsu_input = $form.find('input#bosh_service_url');
  4120. converse.bosh_service_url = $bsu_input.val();
  4121. if (! converse.bosh_service_url) {
  4122. errors = true;
  4123. $bsu_input.addClass('error');
  4124. }
  4125. }
  4126. if (! jid) {
  4127. errors = true;
  4128. $jid_input.addClass('error');
  4129. }
  4130. if (! password) {
  4131. errors = true;
  4132. $pw_input.addClass('error');
  4133. }
  4134. if (errors) { return; }
  4135. this.connect($form, jid, password);
  4136. return false;
  4137. },
  4138. remove: function () {
  4139. this.$tabs.empty();
  4140. this.$el.parent().empty();
  4141. }
  4142. });
  4143. this.ControlBoxToggle = Backbone.View.extend({
  4144. tagName: 'a',
  4145. className: 'toggle-controlbox',
  4146. id: 'toggle-controlbox',
  4147. events: {
  4148. 'click': 'onClick'
  4149. },
  4150. attributes: {
  4151. 'href': "#"
  4152. },
  4153. initialize: function () {
  4154. this.render();
  4155. },
  4156. render: function () {
  4157. $('#conversejs').prepend(this.$el.html(
  4158. converse.templates.controlbox_toggle({
  4159. 'label_toggle': __('Toggle chat')
  4160. })
  4161. ));
  4162. // We let the render method of ControlBoxView decide whether
  4163. // the ControlBox or the Toggle must be shown. This prevents
  4164. // artifacts (i.e. on page load the toggle is shown only to then
  4165. // seconds later be hidden in favor of the control box).
  4166. this.$el.hide();
  4167. return this;
  4168. },
  4169. hide: function (callback) {
  4170. this.$el.fadeOut('fast', callback);
  4171. },
  4172. show: function (callback) {
  4173. this.$el.show('fast', callback);
  4174. },
  4175. showControlBox: function () {
  4176. var controlbox = converse.chatboxes.get('controlbox');
  4177. if (!controlbox) {
  4178. controlbox = converse.addControlBox();
  4179. }
  4180. if (converse.connection.connected) {
  4181. controlbox.save({closed: false});
  4182. } else {
  4183. controlbox.trigger('show');
  4184. }
  4185. },
  4186. onClick: function (e) {
  4187. e.preventDefault();
  4188. if ($("div#controlbox").is(':visible')) {
  4189. var controlbox = converse.chatboxes.get('controlbox');
  4190. if (converse.connection.connected) {
  4191. controlbox.save({closed: true});
  4192. } else {
  4193. controlbox.trigger('hide');
  4194. }
  4195. } else {
  4196. this.showControlBox();
  4197. }
  4198. }
  4199. });
  4200. this.addControlBox = function () {
  4201. return this.chatboxes.add({
  4202. id: 'controlbox',
  4203. box_id: 'controlbox',
  4204. height: this.default_box_height,
  4205. closed: !this.show_controlbox_by_default
  4206. });
  4207. };
  4208. this.initConnection = function () {
  4209. var rid, sid, jid;
  4210. if (this.connection) {
  4211. this.onConnected();
  4212. } else {
  4213. // XXX: it's not yet clear what the order of preference should
  4214. // be between RID and SID received via the initialize method or
  4215. // those received from sessionStorage.
  4216. //
  4217. // What do you we if we receive values from both avenues?
  4218. //
  4219. // Also, what do we do when the keepalive session values are
  4220. // expired? Do we try to fall back?
  4221. if (!this.bosh_service_url) {
  4222. throw("Error: you must supply a value for the bosh_service_url");
  4223. }
  4224. this.connection = new Strophe.Connection(this.bosh_service_url);
  4225. if (this.prebind) {
  4226. if (this.jid && this.sid && this.rid) {
  4227. this.connection.attach(this.jid, this.sid, this.rid, this.onConnect);
  4228. }
  4229. if (!this.keepalive) {
  4230. throw("If you use prebind and don't use keepalive, "+
  4231. "then you MUST supply JID, RID and SID values");
  4232. }
  4233. }
  4234. if (this.keepalive) {
  4235. rid = this.session.get('rid');
  4236. sid = this.session.get('sid');
  4237. jid = this.session.get('jid');
  4238. if (rid && jid && sid) {
  4239. // We have the necessary tokens for resuming a session
  4240. rid += 1;
  4241. this.session.save({rid: rid}); // The RID needs to be increased with each request.
  4242. this.connection.attach(jid, sid, rid, this.onConnect);
  4243. } else if (prebind) {
  4244. delete this.connection;
  4245. this.emit('noResumeableSession');
  4246. }
  4247. }
  4248. }
  4249. };
  4250. this._tearDown = function () {
  4251. /* Remove those views which are only allowed with a valid
  4252. * connection.
  4253. */
  4254. this.initial_presence_sent = false;
  4255. this.roster.off().reset(); // Removes roster contacts
  4256. this.connection.roster._callbacks = []; // Remove all Roster handlers (e.g. rosterHandler)
  4257. this.rosterview.model.off().reset(); // Removes roster groups
  4258. this.rosterview.undelegateEvents().remove();
  4259. this.chatboxes.remove(); // Don't call off(), events won't get re-registered upon reconnect.
  4260. if (this.features) {
  4261. this.features.reset();
  4262. }
  4263. if (this.minimized_chats) {
  4264. this.minimized_chats.undelegateEvents().model.reset();
  4265. this.minimized_chats.removeAll(); // Remove sub-views
  4266. this.minimized_chats.tearDown().remove(); // Remove overview
  4267. delete this.minimized_chats;
  4268. }
  4269. return this;
  4270. };
  4271. this._initialize = function () {
  4272. this.chatboxes = new this.ChatBoxes();
  4273. this.chatboxviews = new this.ChatBoxViews({model: this.chatboxes});
  4274. this.controlboxtoggle = new this.ControlBoxToggle();
  4275. this.otr = new this.OTR();
  4276. this.initSession();
  4277. this.initConnection();
  4278. if (this.connection) {
  4279. this.addControlBox();
  4280. }
  4281. return this;
  4282. };
  4283. // Initialization
  4284. // --------------
  4285. // This is the end of the initialize method.
  4286. this._initialize();
  4287. this.registerGlobalEventHandlers();
  4288. converse.emit('initialized');
  4289. };
  4290. return {
  4291. 'initialize': function (settings, callback) {
  4292. converse.initialize(settings, callback);
  4293. },
  4294. 'getBuddy': function (jid) {
  4295. var contact = converse.roster.get(Strophe.getBareJidFromJid(jid));
  4296. if (contact) {
  4297. return contact.attributes;
  4298. }
  4299. },
  4300. 'getRID': function () {
  4301. if (converse.expose_rid_and_sid && typeof converse.connection !== "undefined") {
  4302. return converse.connection.rid || converse.connection._proto.rid;
  4303. }
  4304. return null;
  4305. },
  4306. 'getSID': function () {
  4307. if (converse.expose_rid_and_sid && typeof converse.connection !== "undefined") {
  4308. return converse.connection.sid || converse.connection._proto.sid;
  4309. }
  4310. return null;
  4311. },
  4312. 'once': function(evt, handler) {
  4313. converse.once(evt, handler);
  4314. },
  4315. 'on': function(evt, handler) {
  4316. converse.on(evt, handler);
  4317. },
  4318. 'off': function(evt, handler) {
  4319. converse.off(evt, handler);
  4320. }
  4321. };
  4322. }));