CCMain.m 255 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687
  1. //
  2. // CCMain.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2014 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCPhotosCameraUpload.h"
  26. #import "CCSynchronize.h"
  27. #import "CCTransfersCell.h"
  28. #import <OCCommunicationLib/OCActivity.h>
  29. #import <OCCommunicationLib/OCNotifications.h>
  30. #import <OCCommunicationLib/OCNotificationsAction.h>
  31. #import <OCCommunicationLib/OCFrameworkConstants.h>
  32. #import <OCCommunicationLib/OCCapabilities.h>
  33. #import "CTAssetCheckmark.h"
  34. #ifdef CUSTOM_BUILD
  35. #import "CustomSwift.h"
  36. #else
  37. #import "Nextcloud-Swift.h"
  38. #endif
  39. #pragma GCC diagnostic ignored "-Wundeclared-selector"
  40. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  41. #define alertCreateFolder 1
  42. #define alertCreateFolderCrypto 2
  43. #define alertRename 3
  44. #define alertOfflineFolder 4
  45. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate, CCActionsDownloadThumbnailDelegate, CCActionsSettingFavoriteDelegate>
  46. {
  47. CCMetadata *_metadata;
  48. BOOL _isRoot;
  49. BOOL _isViewDidLoad;
  50. BOOL _isOfflineServerUrl;
  51. BOOL _isPickerCriptate; // if is cryptated image or video back from picker
  52. BOOL _isSelectedMode;
  53. NSMutableArray *_selectedMetadatas;
  54. NSMutableArray *_queueSelector;
  55. NSUInteger _numSelectedMetadatas;
  56. UIImageView *_ImageTitleHomeCryptoCloud;
  57. UIView *_reMenuBackgroundView;
  58. UITapGestureRecognizer *_singleFingerTap;
  59. NSString *_directoryGroupBy;
  60. NSString *_directoryOrder;
  61. NSUInteger _failedAttempts;
  62. NSDate *_lockUntilDate;
  63. NSString *_fatherPermission;
  64. UIRefreshControl *_refreshControl;
  65. UIDocumentInteractionController *_docController;
  66. CCHud *_hud;
  67. CCHud *_hudDeterminate;
  68. // Datasource
  69. CCSectionDataSourceMetadata *_sectionDataSource;
  70. NSDate *_dateReadDataSource;
  71. // Search
  72. BOOL _isSearchMode;
  73. NSString *_searchFileName;
  74. NSMutableArray *_searchResultMetadatas;
  75. NSString *_depth;
  76. NSString *_noFilesSearchTitle;
  77. NSString *_noFilesSearchDescription;
  78. // Login
  79. CCLoginWeb *_loginWeb;
  80. CCLogin *_loginVC;
  81. }
  82. @end
  83. @implementation CCMain
  84. #pragma --------------------------------------------------------------------------------------------
  85. #pragma mark ===== Init =====
  86. #pragma --------------------------------------------------------------------------------------------
  87. - (id)initWithCoder:(NSCoder *)aDecoder
  88. {
  89. if (self = [super initWithCoder:aDecoder]) {
  90. _directoryOrder = [CCUtility getOrderSettings];
  91. _directoryGroupBy = [CCUtility getGroupBySettings];
  92. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  93. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  94. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  95. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  96. }
  97. return self;
  98. }
  99. #pragma --------------------------------------------------------------------------------------------
  100. #pragma mark ===== View =====
  101. #pragma --------------------------------------------------------------------------------------------
  102. - (void)viewDidLoad
  103. {
  104. [super viewDidLoad];
  105. // init object
  106. _metadata = [CCMetadata new];
  107. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  108. _hudDeterminate = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  109. _selectedMetadatas = [NSMutableArray new];
  110. _queueSelector = [NSMutableArray new];
  111. _isViewDidLoad = YES;
  112. _fatherPermission = @"";
  113. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  114. _searchResultMetadatas = [NSMutableArray new];
  115. _searchFileName = @"";
  116. _depth = @"0";
  117. _noFilesSearchTitle = @"";
  118. _noFilesSearchDescription = @"";
  119. // delegate
  120. self.tableView.delegate = self;
  121. self.tableView.tableFooterView = [UIView new];
  122. self.tableView.separatorColor = [NCBrandColor sharedInstance].seperator;
  123. self.tableView.emptyDataSetDelegate = self;
  124. self.tableView.emptyDataSetSource = self;
  125. self.searchController.delegate = self;
  126. self.searchController.searchBar.delegate = self;
  127. [[CCNetworking sharedNetworking] settingDelegate:self];
  128. // Custom Cell
  129. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  130. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  131. // long press recognizer TableView
  132. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  133. [self.tableView addGestureRecognizer:longPressRecognizer];
  134. // Pull-to-Refresh
  135. [self createRefreshControl];
  136. // Register for 3D Touch Previewing if available
  137. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  138. {
  139. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  140. }
  141. // Back Button
  142. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]])
  143. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:[NCBrandImages sharedInstance].navigationLogo] style:UIBarButtonItemStylePlain target:nil action:nil];
  144. // reMenu Background
  145. _reMenuBackgroundView = [[UIView alloc] init];
  146. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  147. // if this is not Main (the Main uses inizializeMain)
  148. if (_isRoot == NO && app.activeAccount.length > 0) {
  149. // Settings this folder & delegate & Loading datasource
  150. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  151. // Load Datasource
  152. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  153. // Read Folder
  154. [self readFolderWithForced:NO serverUrl:_serverUrl];
  155. }
  156. // Version Server
  157. app.serverVersion = [CCCoreData getServerVersionMajorActiveAccount:app.activeAccount];
  158. // Title
  159. [self setTitle];
  160. // Search
  161. self.definesPresentationContext = YES;
  162. self.searchController.searchResultsUpdater = self;
  163. self.searchController.dimsBackgroundDuringPresentation = NO;
  164. self.tableView.tableHeaderView = self.searchController.searchBar;
  165. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].seperator;
  166. [self.searchController.searchBar sizeToFit];
  167. self.searchController.searchBar.delegate = self;
  168. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_this_folder_",nil);
  169. if (app.serverVersion >= 12) {
  170. if (_isRoot)
  171. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),NSLocalizedString(@"_search_all_folders_",nil), nil];
  172. else
  173. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),NSLocalizedString(@"_search_sub_folder_",nil), nil];
  174. } else {
  175. self.searchController.searchBar.scopeButtonTitles = nil;
  176. }
  177. // Hide Search Filed on Load
  178. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  179. }
  180. // Apparirà
  181. - (void)viewWillAppear:(BOOL)animated
  182. {
  183. [super viewWillAppear:animated];
  184. // test
  185. if (app.activeAccount.length == 0)
  186. return;
  187. // Settings this folder & delegate & Loading datasource
  188. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  189. [[CCNetworking sharedNetworking] settingDelegate:self];
  190. // Color
  191. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  192. [app aspectTabBar:self.tabBarController.tabBar hidden:NO];
  193. // Menu e Bar
  194. [self createReMainMenu];
  195. [self createReSelectMenu];
  196. if (_isSelectedMode)
  197. [self setUINavigationBarSelected];
  198. else
  199. [self setUINavigationBarDefault];
  200. // Plus Button
  201. [app plusButtonVisibile:true];
  202. }
  203. // E' arrivato
  204. - (void)viewDidAppear:(BOOL)animated
  205. {
  206. [super viewDidAppear:animated];
  207. // Active Main
  208. app.activeMain = self;
  209. // Test viewDidLoad
  210. if (_isViewDidLoad) {
  211. _isViewDidLoad = NO;
  212. } else {
  213. if (app.activeAccount.length > 0) {
  214. // Load Datasource
  215. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  216. // Read Folder
  217. [self readFolderWithForced:NO serverUrl:_serverUrl];
  218. }
  219. }
  220. // Title
  221. [self setTitle];
  222. }
  223. - (void)viewWillDisappear:(BOOL)animated
  224. {
  225. [super viewWillDisappear:animated];
  226. [self closeAllMenu];
  227. }
  228. - (void)didReceiveMemoryWarning
  229. {
  230. [super didReceiveMemoryWarning];
  231. // Dispose of any resources that can be recreated.
  232. }
  233. - (BOOL)prefersStatusBarHidden
  234. {
  235. return NO;
  236. }
  237. // detect scroll for remove keyboard in search mode
  238. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  239. {
  240. if (_isSearchMode && scrollView == self.tableView) {
  241. [self.searchController.searchBar endEditing:YES];
  242. }
  243. }
  244. #pragma --------------------------------------------------------------------------------------------
  245. #pragma mark ===== Initizlize Mail =====
  246. #pragma --------------------------------------------------------------------------------------------
  247. - (void)initializeMain:(NSNotification *)notification
  248. {
  249. _directoryGroupBy = nil;
  250. _directoryOrder = nil;
  251. _dateReadDataSource = nil;
  252. // test
  253. if (app.activeAccount.length == 0)
  254. return;
  255. if ([app.listMainVC count] == 0 || _isRoot) {
  256. // This is Root
  257. _isRoot = YES;
  258. // Crypto Mode
  259. if ([[CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]] length] == 0) {
  260. app.isCryptoCloudMode = NO;
  261. } else {
  262. app.isCryptoCloudMode = YES;
  263. }
  264. // go Home
  265. [self.navigationController popToRootViewControllerAnimated:NO];
  266. // Remove search mode
  267. [self cancelSearchBar];
  268. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  269. _isFolderEncrypted = NO;
  270. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  271. // add list
  272. [app.listMainVC setObject:self forKey:_serverUrl];
  273. // setting Networking
  274. [[CCNetworking sharedNetworking] settingDelegate:self];
  275. [[CCNetworking sharedNetworking] settingAccount];
  276. // populate shared Link & User variable
  277. [CCCoreData populateSharesVariableFromDBActiveAccount:app.activeAccount sharesLink:app.sharesLink sharesUserAndGroup:app.sharesUserAndGroup];
  278. // Load Datasource
  279. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  280. // Load Folder
  281. [self readFolderWithForced:NO serverUrl:_serverUrl];
  282. // Load photo datasorce
  283. if (app.activePhotosCameraUpload)
  284. [app.activePhotosCameraUpload reloadDatasourceForced];
  285. // remove all of detail
  286. if (app.activeDetail)
  287. [app.activeDetail removeAllView];
  288. // remove all Notification Messages
  289. [app.listOfNotifications removeAllObjects];
  290. // home main
  291. app.homeMain = self;
  292. // Initializations
  293. [app applicationInitialized];
  294. } else {
  295. // reload datasource
  296. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  297. }
  298. }
  299. #pragma --------------------------------------------------------------------------------------------
  300. #pragma mark ==== DZNEmptyDataSetSource ====
  301. #pragma --------------------------------------------------------------------------------------------
  302. /*
  303. - (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView
  304. {
  305. if(_isSearchMode)
  306. return NO;
  307. else
  308. return YES;
  309. }
  310. */
  311. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  312. {
  313. return YES;
  314. }
  315. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  316. {
  317. return [UIColor whiteColor];
  318. }
  319. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  320. {
  321. if (_isSearchMode)
  322. return [UIImage imageNamed:image_searchBig];
  323. else
  324. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_filesNoFiles] color:[NCBrandColor sharedInstance].brand];
  325. }
  326. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  327. {
  328. NSString *text;
  329. if (_isSearchMode)
  330. text = _noFilesSearchTitle;
  331. else
  332. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  333. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  334. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  335. }
  336. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  337. {
  338. NSString *text;
  339. if (_isSearchMode)
  340. text = _noFilesSearchDescription;
  341. else
  342. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  343. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  344. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  345. paragraph.alignment = NSTextAlignmentCenter;
  346. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  347. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  348. }
  349. #pragma --------------------------------------------------------------------------------------------
  350. #pragma mark ===== AlertView =====
  351. #pragma --------------------------------------------------------------------------------------------
  352. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  353. {
  354. [alertView dismissWithClickedButtonIndex:buttonIndex animated:YES];
  355. if (alertView.tag == alertCreateFolder && buttonIndex == 1) [self createFolder:[alertView textFieldAtIndex:0].text folderCameraUpload:NO];
  356. if (alertView.tag == alertCreateFolderCrypto && buttonIndex == 1) [self createFolderEncrypted:[alertView textFieldAtIndex:0].text];
  357. if (alertView.tag == alertRename && buttonIndex == 1) {
  358. if ([_metadata.model isEqualToString:@"note"]) {
  359. [self renameNote:_metadata fileName:[alertView textFieldAtIndex:0].text];
  360. } else {
  361. [self renameFile:_metadata fileName:[alertView textFieldAtIndex:0].text];
  362. }
  363. }
  364. if (alertView.tag == alertOfflineFolder && buttonIndex == 1) {
  365. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  366. NSString *dir = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  367. [[CCSynchronize sharedSynchronize] addOfflineFolder:dir];
  368. [self performSelector:@selector(reloadDatasource) withObject:nil];
  369. }
  370. }
  371. // accept only number char > 0
  372. - (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
  373. {
  374. /* Retrieve a text field at an index -
  375. raises NSRangeException when textFieldIndex is out-of-bounds.
  376. The field at index 0 will be the first text field
  377. (the single field or the login field),
  378. The field at index 1 will be the password field. */
  379. /*
  380. 1> Get the Text Field in alertview
  381. 2> Get the text of that Text Field
  382. 3> Verify that text length
  383. 4> return YES or NO Based on the length
  384. */
  385. if (alertView.tag == alertOfflineFolder) return YES;
  386. else return ([[[alertView textFieldAtIndex:0] text] length]>0)?YES:NO;
  387. }
  388. #pragma --------------------------------------------------------------------------------------------
  389. #pragma mark ===== Graphic Window =====
  390. #pragma --------------------------------------------------------------------------------------------
  391. - (void)createRefreshControl
  392. {
  393. _refreshControl = [UIRefreshControl new];
  394. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  395. _refreshControl.backgroundColor = [UIColor colorWithRed:235.0/255.0 green:235.0/255.0 blue:235.0/255.0 alpha:1.0];
  396. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  397. [self setRefreshControl:_refreshControl];
  398. }
  399. - (void)deleteRefreshControl
  400. {
  401. [_refreshControl endRefreshing];
  402. self.refreshControl = nil;
  403. }
  404. - (void)refreshControlTarget
  405. {
  406. [self readFolderWithForced:YES serverUrl:_serverUrl];
  407. // Actuate `Peek` feedback (weak boom)
  408. AudioServicesPlaySystemSound(1519);
  409. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  410. }
  411. - (void)setTitle
  412. {
  413. // Color text self.navigationItem.title
  414. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  415. if (_isSelectedMode) {
  416. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  417. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  418. self.navigationItem.titleView = nil;
  419. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  420. } else {
  421. // we are in home : LOGO BRAND
  422. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  423. self.navigationItem.title = nil;
  424. if ([app.reachability isReachable] == NO) _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NCBrandImages sharedInstance].navigationLogoOffline]];
  425. else _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NCBrandImages sharedInstance].navigationLogo]];
  426. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  427. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuLogo)];
  428. [singleTap setNumberOfTapsRequired:1];
  429. [_ImageTitleHomeCryptoCloud addGestureRecognizer:singleTap];
  430. self.navigationItem.titleView = _ImageTitleHomeCryptoCloud;
  431. } else {
  432. self.navigationItem.title = _titleMain;
  433. }
  434. }
  435. }
  436. - (void)setUINavigationBarDefault
  437. {
  438. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  439. UIBarButtonItem *buttonMore, *buttonNotification;
  440. // =
  441. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:image_navigationControllerMenu] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  442. buttonMore.enabled = true;
  443. // <
  444. self.navigationController.navigationBar.hidden = NO;
  445. // Notification
  446. if ([app.listOfNotifications count] > 0) {
  447. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:image_notification] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  448. buttonNotification.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  449. buttonNotification.enabled = true;
  450. }
  451. if (buttonNotification)
  452. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  453. else
  454. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  455. self.navigationItem.leftBarButtonItem = nil;
  456. }
  457. - (void)setUINavigationBarSelected
  458. {
  459. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  460. UIImage *icon = [UIImage imageNamed:image_navigationControllerMenu];
  461. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  462. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  463. self.navigationItem.leftBarButtonItem = leftButton;
  464. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  465. }
  466. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  467. {
  468. [self closeAllMenu];
  469. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  470. }];
  471. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  472. }
  473. - (void)cancelSelect
  474. {
  475. [self tableViewSelect:NO];
  476. }
  477. - (void)closeAllMenu
  478. {
  479. // close Menu
  480. [app.reSelectMenu close];
  481. [app.reMainMenu close];
  482. // Close Menu Logo
  483. [CCMenuAccount dismissMenu];
  484. }
  485. #pragma --------------------------------------------------------------------------------------------
  486. #pragma mark ===== Document Picker =====
  487. #pragma --------------------------------------------------------------------------------------------
  488. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  489. {
  490. NSLog(@"Cancelled");
  491. }
  492. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  493. {
  494. NSLog(@"Cancelled");
  495. }
  496. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  497. {
  498. documentPicker.delegate = self;
  499. [self presentViewController:documentPicker animated:YES completion:nil];
  500. }
  501. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  502. {
  503. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  504. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  505. __block NSError *error;
  506. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  507. NSString *fileName = [url lastPathComponent];
  508. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileName];
  509. NSData *data = [NSData dataWithContentsOfURL:newURL];
  510. if (data && error == nil) {
  511. if ([data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error]) {
  512. // Upload File
  513. [[CCNetworking sharedNetworking] uploadFile:fileName serverUrl:_serverUrl cryptated:_isPickerCriptate onlyPlist:NO session:k_upload_session taskStatus: k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  514. } else {
  515. [app messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  516. }
  517. } else {
  518. [app messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  519. }
  520. }];
  521. }
  522. }
  523. - (void)openImportDocumentPicker
  524. {
  525. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  526. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  527. documentProviderMenu.popoverPresentationController.sourceView = self.view;
  528. documentProviderMenu.popoverPresentationController.sourceRect = self.view.bounds;
  529. documentProviderMenu.delegate = self;
  530. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  531. }
  532. #pragma --------------------------------------------------------------------------------------------
  533. #pragma mark ===== Assets Picker =====
  534. #pragma --------------------------------------------------------------------------------------------
  535. - (void)openAssetsPickerController
  536. {
  537. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  538. checkmark.tintColor = [NCBrandColor sharedInstance].brand;
  539. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeTop];
  540. UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedIn:[CTAssetsPickerController class], nil];
  541. [app aspectNavigationControllerBar:navBar encrypted:NO online:YES hidden:NO];
  542. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
  543. dispatch_async(dispatch_get_main_queue(), ^{
  544. // init picker
  545. CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
  546. // set delegate
  547. picker.delegate = self;
  548. // to show selection order
  549. //picker.showsSelectionIndex = YES;
  550. // to present picker as a form sheet in iPad
  551. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  552. picker.modalPresentationStyle = UIModalPresentationFormSheet;
  553. // present picker
  554. [self presentViewController:picker animated:YES completion:nil];
  555. });
  556. }];
  557. }
  558. - (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSMutableArray *)assets
  559. {
  560. [picker dismissViewControllerAnimated:YES completion:^{
  561. CreateFormUploadAssets *form = [[CreateFormUploadAssets alloc] init:_titleMain serverUrl:_serverUrl assets:assets cryptated:_isPickerCriptate session:k_upload_session];
  562. form.title = NSLocalizedString(@"_upload_photos_videos_", nil);
  563. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  564. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  565. //navController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
  566. [self presentViewController:navigationController animated:YES completion:nil];
  567. }];
  568. }
  569. #pragma --------------------------------------------------------------------------------------------
  570. #pragma mark ===== UIDocumentInteractionControllerDelegate =====
  571. #pragma --------------------------------------------------------------------------------------------
  572. - (void)documentInteractionControllerDidDismissOptionsMenu:(UIDocumentInteractionController *)controller
  573. {
  574. // evitiamo il rimando della eventuale photo e/o video
  575. if ([CCCoreData getCameraUploadActiveAccount:app.activeAccount]) {
  576. [CCCoreData setCameraUploadDatePhoto:[NSDate date]];
  577. [CCCoreData setCameraUploadDateVideo:[NSDate date]];
  578. }
  579. }
  580. #pragma --------------------------------------------------------------------------------------------
  581. #pragma mark ===== UnZipFile =====
  582. #pragma --------------------------------------------------------------------------------------------
  583. - (void)unZipFile:(NSString *)fileID
  584. {
  585. [_hudDeterminate visibleHudTitle:NSLocalizedString(@"_unzip_in_progress_", nil) mode:MBProgressHUDModeDeterminate color:nil];
  586. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  587. NSString *fileZip = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID];
  588. [SSZipArchive unzipFileAtPath:fileZip toDestination:[CCUtility getDirectoryLocal] overwrite:YES password:nil progressHandler:^(NSString *entry, unz_file_info zipInfo, long entryNumber, long total) {
  589. dispatch_async(dispatch_get_main_queue(), ^{
  590. float progress = (float) entryNumber / (float)total;
  591. [_hudDeterminate progress:progress];
  592. });
  593. } completionHandler:^(NSString *path, BOOL succeeded, NSError *error) {
  594. dispatch_async(dispatch_get_main_queue(), ^{
  595. [_hudDeterminate hideHud];
  596. if (succeeded) [app messageNotification:@"_info_" description:@"_file_unpacked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess];
  597. else [app messageNotification:@"_error_" description:[NSString stringWithFormat:@"Error %ld", (long)error.code] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  598. });
  599. }];
  600. });
  601. }
  602. #pragma --------------------------------------------------------------------------------------------
  603. #pragma mark ===== Create New (OpenModel) =====
  604. #pragma --------------------------------------------------------------------------------------------
  605. - (void)openModel:(NSString *)tipo isNew:(BOOL)isnew
  606. {
  607. UIViewController *viewController;
  608. NSString *fileName, *uuid, *fileID, *serverUrl;
  609. NSIndexPath * index = [self.tableView indexPathForSelectedRow];
  610. [self.tableView deselectRowAtIndexPath:index animated:NO];
  611. if (isnew) {
  612. fileName = nil;
  613. uuid = [CCUtility getUUID];
  614. fileID = nil;
  615. serverUrl = _serverUrl;
  616. } else {
  617. fileName = _metadata.fileName;
  618. uuid = _metadata.uuid;
  619. fileID = _metadata.fileID;
  620. serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  621. }
  622. if ([tipo isEqualToString:@"cartadicredito"])
  623. viewController = [[CCCartaDiCredito alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  624. if ([tipo isEqualToString:@"bancomat"])
  625. viewController = [[CCBancomat alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  626. if ([tipo isEqualToString:@"contocorrente"])
  627. viewController = [[CCContoCorrente alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  628. if ([tipo isEqualToString:@"accountweb"])
  629. viewController = [[CCAccountWeb alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  630. if ([tipo isEqualToString:@"patenteguida"])
  631. viewController = [[CCPatenteGuida alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  632. if ([tipo isEqualToString:@"cartaidentita"])
  633. viewController = [[CCCartaIdentita alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  634. if ([tipo isEqualToString:@"passaporto"])
  635. viewController = [[CCPassaporto alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  636. if ([tipo isEqualToString:@"note"]) {
  637. viewController = [[CCNote alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  638. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  639. [self presentViewController:navigationController animated:YES completion:nil];
  640. } else {
  641. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  642. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  643. [self presentViewController:navigationController animated:YES completion:nil];
  644. }
  645. }
  646. // New folder or new photo or video
  647. - (void)returnCreate:(NSInteger)type
  648. {
  649. switch (type) {
  650. /* PLAIN */
  651. case k_returnCreateFolderPlain: {
  652. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  653. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  654. alertView.tag = alertCreateFolder;
  655. [alertView show];
  656. }
  657. break;
  658. case k_returnCreateFotoVideoPlain: {
  659. _isPickerCriptate = false;
  660. [self openAssetsPickerController];
  661. }
  662. break;
  663. case k_returnCreateFilePlain: {
  664. _isPickerCriptate = false;
  665. [self openImportDocumentPicker];
  666. }
  667. break;
  668. /* ENCRYPTED */
  669. case k_returnCreateFolderEncrypted: {
  670. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  671. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  672. alertView.tag = alertCreateFolderCrypto;
  673. [alertView show];
  674. }
  675. break;
  676. case k_returnCreateFotoVideoEncrypted: {
  677. _isPickerCriptate = true;
  678. [self openAssetsPickerController];
  679. }
  680. break;
  681. case k_returnCreateFileEncrypted: {
  682. _isPickerCriptate = true;
  683. [self openImportDocumentPicker];
  684. }
  685. break;
  686. /* UTILITY */
  687. case k_returnNote:
  688. [self openModel:@"note" isNew:true];
  689. break;
  690. case k_returnAccountWeb:
  691. [self openModel:@"accountweb" isNew:true];
  692. break;
  693. /* BANK */
  694. case k_returnCartaDiCredito:
  695. [self openModel:@"cartadicredito" isNew:true];
  696. break;
  697. case k_returnBancomat:
  698. [self openModel:@"bancomat" isNew:true];
  699. break;
  700. case k_returnContoCorrente:
  701. [self openModel:@"contocorrente" isNew:true];
  702. break;
  703. /* DOCUMENT */
  704. case k_returnPatenteGuida:
  705. [self openModel:@"patenteguida" isNew:true];
  706. break;
  707. case k_returnCartaIdentita:
  708. [self openModel:@"cartaidentita" isNew:true];
  709. break;
  710. case k_returnPassaporto:
  711. [self openModel:@"passaporto" isNew:true];
  712. break;
  713. }
  714. }
  715. #pragma --------------------------------------------------------------------------------------------
  716. #pragma mark ===== Save selected File =====
  717. #pragma --------------------------------------------------------------------------------------------
  718. -(void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  719. {
  720. if (error)
  721. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  722. else
  723. [app messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess];
  724. }
  725. - (void)saveSelectedFiles
  726. {
  727. NSLog(@"[LOG] Start download selected files ...");
  728. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  729. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  730. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  731. for (CCMetadata *metadata in metadatas) {
  732. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file] && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  733. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  734. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorSave selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  735. }
  736. }
  737. [_hud hideHud];
  738. });
  739. [self tableViewSelect:NO];
  740. }
  741. #pragma --------------------------------------------------------------------------------------------
  742. #pragma mark ===== Change Password =====
  743. #pragma --------------------------------------------------------------------------------------------
  744. - (void) loginSuccess:(NSInteger)loginType
  745. {
  746. [self readFolderWithForced:YES serverUrl:_serverUrl];
  747. }
  748. - (void)changePasswordAccount
  749. {
  750. // Brand
  751. if (k_option_use_login_web) {
  752. _loginWeb = [CCLoginWeb new];
  753. _loginWeb.delegate = self;
  754. _loginWeb.loginType = loginModifyPasswordUser;
  755. dispatch_async(dispatch_get_main_queue(), ^ {
  756. [_loginWeb presentModalWithDefaultTheme:self];
  757. });
  758. } else {
  759. _loginVC = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  760. _loginVC.delegate = self;
  761. _loginVC.loginType = loginModifyPasswordUser;
  762. [self presentViewController:_loginVC animated:YES completion:nil];
  763. }
  764. }
  765. #pragma mark -
  766. #pragma --------------------------------------------------------------------------------------------
  767. #pragma mark ===== Peek & Pop =====
  768. #pragma --------------------------------------------------------------------------------------------
  769. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  770. {
  771. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  772. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  773. if (metadata.thumbnailExists && !metadata.cryptated) {
  774. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  775. if (cell) {
  776. previewingContext.sourceRect = cell.frame;
  777. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  778. vc.delegate = self;
  779. vc.metadata = metadata;
  780. return vc;
  781. }
  782. }
  783. return nil;
  784. }
  785. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  786. {
  787. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  788. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  789. }
  790. #pragma mark -
  791. #pragma --------------------------------------------------------------------------------------------
  792. #pragma mark ==== External Sites ====
  793. #pragma --------------------------------------------------------------------------------------------
  794. - (void)getExternalSitesServerSuccess:(NSArray *)listOfExternalSites
  795. {
  796. [CCCoreData deleteAllExternalSitesForAccount:app.activeAccount];
  797. for (OCExternalSites *tableExternalSites in listOfExternalSites)
  798. [CCCoreData addExternalSites:tableExternalSites account:app.activeAccount];
  799. }
  800. - (void)getExternalSitesServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  801. {
  802. NSLog(@"[LOG] No External Sites found");
  803. }
  804. #pragma --------------------------------------------------------------------------------------------
  805. #pragma mark ==== Activity ====
  806. #pragma --------------------------------------------------------------------------------------------
  807. - (void)getActivityServerSuccess:(NSArray *)listOfActivity
  808. {
  809. for (OCActivity *activity in listOfActivity)
  810. [CCCoreData addActivityServer:activity account:app.activeAccount];
  811. // Reload Activity Data Source
  812. [app.activeActivity reloadDatasource];
  813. }
  814. - (void)getActivityServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  815. {
  816. NSLog(@"[LOG] No Activity found");
  817. }
  818. #pragma --------------------------------------------------------------------------------------------
  819. #pragma mark ==== Notification ====
  820. #pragma --------------------------------------------------------------------------------------------
  821. - (void)getNotificationServerSuccess:(NSArray *)listOfNotifications
  822. {
  823. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  824. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  825. // Order by date
  826. NSArray *sortedListOfNotifications = [listOfNotifications sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  827. OCNotifications *notification1 = obj1, *notification2 = obj2;
  828. return [notification2.date compare: notification1.date];
  829. }];
  830. // verify if listOfNotifications is changed
  831. NSString *old = @"", *new = @"";
  832. for (OCNotifications *notification in listOfNotifications)
  833. new = [new stringByAppendingString:@(notification.idNotification).stringValue];
  834. for (OCNotifications *notification in appDelegate.listOfNotifications)
  835. old = [old stringByAppendingString:@(notification.idNotification).stringValue];
  836. if (![new isEqualToString:old]) {
  837. appDelegate.listOfNotifications = [[NSMutableArray alloc] initWithArray:sortedListOfNotifications];
  838. // reload Notification view
  839. dispatch_async(dispatch_get_main_queue(), ^{
  840. [[NSNotificationCenter defaultCenter] postNotificationName:@"notificationReloadData" object:nil];
  841. });
  842. }
  843. // Update NavigationBar
  844. if (!_isSelectedMode) {
  845. [self performSelectorOnMainThread:@selector(setUINavigationBarDefault) withObject:nil waitUntilDone:NO];
  846. }
  847. });
  848. }
  849. - (void)getNotificationServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  850. {
  851. // Update NavigationBar
  852. if (!_isSelectedMode)
  853. [self setUINavigationBarDefault];
  854. }
  855. - (void)viewNotification
  856. {
  857. if ([app.listOfNotifications count] > 0) {
  858. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  859. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  860. [self presentViewController:notificationVC animated:YES completion:nil];
  861. }
  862. }
  863. #pragma --------------------------------------------------------------------------------------------
  864. #pragma mark ==== Request Server ====
  865. #pragma --------------------------------------------------------------------------------------------
  866. - (void)getUserProfileSuccess:(CCMetadataNet *)metadataNet userProfile:(OCUserProfile *)userProfile
  867. {
  868. [CCCoreData setUserProfileActiveAccount:metadataNet.account userProfile:userProfile];
  869. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  870. NSString *address = [NSString stringWithFormat:@"%@/index.php/avatar/%@/128", app.activeUrl, app.activeUser];
  871. UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  872. if (avatar)
  873. [UIImagePNGRepresentation(avatar) writeToFile:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] atomically:YES];
  874. else
  875. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] error:nil];
  876. });
  877. }
  878. - (void)getCapabilitiesOfServerSuccess:(OCCapabilities *)capabilities
  879. {
  880. // Change Theming color
  881. [app settingThemingColor:capabilities.themingColor];
  882. [CCCoreData addCapabilities:capabilities account:app.activeAccount];
  883. // Download Theming Background
  884. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  885. UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  886. if (themingBackground)
  887. [UIImagePNGRepresentation(themingBackground) writeToFile:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] atomically:YES];
  888. else
  889. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] error:nil];
  890. });
  891. // Search bar if change version
  892. if (app.serverVersion != capabilities.versionMajor) {
  893. [self cancelSearchBar];
  894. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  895. if (capabilities.versionMajor >= 12) {
  896. if (_isRoot)
  897. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_all_folders_",nil);
  898. else
  899. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_sub_folder_",nil);
  900. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),self.searchController.searchBar.placeholder, nil];
  901. } else {
  902. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_this_folder_",nil);
  903. self.searchController.searchBar.scopeButtonTitles = nil;
  904. }
  905. _depth = @"0";
  906. });
  907. }
  908. // External Sites
  909. if (capabilities.isExternalSitesServerEnabled) {
  910. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  911. metadataNet.action = actionGetExternalSitesServer;
  912. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  913. }
  914. [CCCoreData setServerVersionActiveAccount:app.activeAccount versionMajor:capabilities.versionMajor versionMinor:capabilities.versionMinor versionMicro:capabilities.versionMicro];
  915. app.serverVersion = capabilities.versionMajor;
  916. }
  917. - (void)getFeaturesSupportedByServerSuccess:(BOOL)hasCapabilitiesSupport hasForbiddenCharactersSupport:(BOOL)hasForbiddenCharactersSupport hasShareSupport:(BOOL)hasShareSupport hasShareeSupport:(BOOL)hasShareeSupport
  918. {
  919. app.hasServerCapabilitiesSupport = hasCapabilitiesSupport;
  920. app.hasServerForbiddenCharactersSupport = hasForbiddenCharactersSupport;
  921. app.hasServerShareSupport = hasShareSupport;
  922. app.hasServerShareeSupport = hasShareeSupport;
  923. if (hasShareSupport || hasShareeSupport)
  924. [self requestSharedByServer];
  925. }
  926. - (void)getInfoServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  927. {
  928. if (errorCode == 401)
  929. [self changePasswordAccount];
  930. }
  931. - (void)requestServerInformation
  932. {
  933. // test
  934. if (app.activeAccount.length == 0)
  935. return;
  936. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  937. [app.sharesID removeAllObjects];
  938. app.hasServerForbiddenCharactersSupport = YES;
  939. app.hasServerShareSupport = YES;
  940. metadataNet.action = actionGetFeaturesSuppServer;
  941. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  942. metadataNet.action = actionGetCapabilities;
  943. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  944. metadataNet.action = actionGetNotificationServer;
  945. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  946. metadataNet.action = actionGetUserProfile;
  947. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  948. metadataNet.action = actionGetActivityServer;
  949. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  950. }
  951. #pragma --------------------------------------------------------------------------------------------
  952. #pragma mark ==== Download Thumbnail Delegate ====
  953. #pragma --------------------------------------------------------------------------------------------
  954. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  955. {
  956. __block CCCellMain *cell;
  957. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  958. if (indexPath && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]]) {
  959. cell = [self.tableView cellForRowAtIndexPath:indexPath];
  960. cell.fileImageView.image = [app.icoImagesCache objectForKey:metadataNet.fileID];
  961. if (cell.fileImageView.image == nil) {
  962. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  963. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]];
  964. [app.icoImagesCache setObject:image forKey:metadataNet.fileID];
  965. });
  966. }
  967. }
  968. }
  969. #pragma --------------------------------------------------------------------------------------------
  970. #pragma mark ==== Download ====
  971. #pragma --------------------------------------------------------------------------------------------
  972. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  973. {
  974. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  975. // File do not exists on server, remove in local
  976. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  977. [CCCoreData deleteFile:metadata serverUrl:serverUrl directoryUser:app.directoryUser activeAccount:app.activeAccount];
  978. }
  979. if ([selector isEqualToString:selectorLoadViewImage]) {
  980. dispatch_async(dispatch_get_main_queue(), ^{
  981. // Updating Detail
  982. if (app.activeDetail)
  983. [app.activeDetail downloadPhotoBrowserFailure:errorCode];
  984. // Updating Photos
  985. if (app.activePhotosCameraUpload)
  986. [app.activePhotosCameraUpload downloadFileFailure:errorCode];
  987. });
  988. } else {
  989. if (errorCode != kCFURLErrorCancelled)
  990. [app messageNotification:@"_download_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  991. }
  992. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  993. }
  994. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  995. {
  996. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  997. if (metadata == nil) return;
  998. // Download
  999. if ([selector isEqualToString:selectorDownloadFile]) {
  1000. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1001. }
  1002. // Synchronized
  1003. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  1004. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1005. }
  1006. // add Favorite
  1007. if ([selector isEqualToString:selectorAddFavorite]) {
  1008. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  1009. }
  1010. // add Offline
  1011. if ([selector isEqualToString:selectorAddOffline]) {
  1012. [CCCoreData setOfflineLocalFileID:metadata.fileID offline:YES activeAccount:app.activeAccount];
  1013. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1014. }
  1015. // encrypted file
  1016. if ([selector isEqualToString:selectorEncryptFile]) {
  1017. [self encryptedFile:metadata];
  1018. }
  1019. // decrypted file
  1020. if ([selector isEqualToString:selectorDecryptFile]) {
  1021. [self decryptedFile:metadata];
  1022. }
  1023. // open View File
  1024. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1025. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1026. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  1027. [self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  1028. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  1029. selector = selectorOpenIn;
  1030. } else {
  1031. _metadata = metadata;
  1032. if ([self shouldPerformSegue])
  1033. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  1034. }
  1035. }
  1036. // addLocal
  1037. if ([selector isEqualToString:selectorAddLocal]) {
  1038. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  1039. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  1040. [CCGraphics saveIcoWithFileID:metadata.fileNamePrint image:image writeToFile:nil copy:YES move:NO fromPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/.%@.ico", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  1041. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess];
  1042. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1043. }
  1044. // Open with...
  1045. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1046. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1047. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1048. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1049. NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint]];
  1050. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  1051. _docController.delegate = self;
  1052. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  1053. }
  1054. // Save to Photo Album
  1055. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1056. NSString *file = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1057. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  1058. // evitiamo il rimando photo
  1059. [CCCoreData setCameraUploadDatePhoto:[NSDate date]];
  1060. UIImage *image = [UIImage imageWithContentsOfFile:file];
  1061. if (image)
  1062. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1063. else
  1064. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1065. }
  1066. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  1067. // we avoid the cross-reference video
  1068. [CCCoreData setCameraUploadDateVideo:[NSDate date]];
  1069. [[NSFileManager defaultManager] linkItemAtPath:file toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1070. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint])) {
  1071. UISaveVideoAtPathToSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint], self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1072. } else {
  1073. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1074. }
  1075. }
  1076. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1077. }
  1078. // Copy File
  1079. if ([selector isEqualToString:selectorLoadCopy]) {
  1080. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1081. [self copyFileToPasteboard:metadata];
  1082. }
  1083. // download and view a template
  1084. if ([selector isEqualToString:selectorLoadModelView]) {
  1085. [CCCoreData downloadFilePlist:metadata activeAccount:app.activeAccount activeUrl:app.activeUrl directoryUser:app.directoryUser];
  1086. [self openModel:metadata.model isNew:false];
  1087. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1088. }
  1089. //download file plist
  1090. if ([selector isEqualToString:selectorLoadPlist]) {
  1091. [CCCoreData downloadFilePlist:metadata activeAccount:app.activeAccount activeUrl:app.activeUrl directoryUser:app.directoryUser];
  1092. long countSelectorLoadPlist = 0;
  1093. for (NSOperation *operation in [app.netQueue operations]) {
  1094. if ([((OCnetworking *)operation).metadataNet.selector isEqualToString:selectorLoadPlist])
  1095. countSelectorLoadPlist++;
  1096. }
  1097. if ((countSelectorLoadPlist == 0 || countSelectorLoadPlist % k_maxConcurrentOperation == 0) && [metadata.directoryID isEqualToString:[CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount]]) {
  1098. dispatch_async(dispatch_get_main_queue(), ^{
  1099. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1100. });
  1101. }
  1102. }
  1103. //selectorLoadViewImage
  1104. if ([selector isEqualToString:selectorLoadViewImage]) {
  1105. dispatch_async(dispatch_get_main_queue(), ^{
  1106. // Detail
  1107. if (app.activeDetail)
  1108. [app.activeDetail downloadPhotoBrowserSuccess:metadata selector:selector];
  1109. // Photos
  1110. if (app.activePhotosCameraUpload)
  1111. [app.activePhotosCameraUpload downloadFileSuccess:metadata];
  1112. });
  1113. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1114. }
  1115. // if exists postselector call self with selectorPost
  1116. if ([selectorPost length] > 0)
  1117. [self downloadFileSuccess:fileID serverUrl:serverUrl selector:selectorPost selectorPost:nil];
  1118. }
  1119. - (void)downloadSelectedFiles
  1120. {
  1121. NSLog(@"[LOG] Start download selected files ...");
  1122. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1123. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1124. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1125. for (CCMetadata *metadata in selectedMetadatas) {
  1126. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file]) {
  1127. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1128. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDownloadFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1129. }
  1130. }
  1131. [_hud hideHud];
  1132. });
  1133. [self tableViewSelect:NO];
  1134. }
  1135. - (void)downloadPlist:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1136. {
  1137. NSArray *records = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND ((session == NULL) OR (session == ''))", app.activeAccount, directoryID] context:nil];
  1138. for (TableMetadata *recordMetadata in records) {
  1139. if ([CCUtility isCryptoPlistString:recordMetadata.fileName] && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, recordMetadata.fileName]] == NO && [recordMetadata.session length] == 0) {
  1140. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1141. metadataNet.action = actionDownloadFile;
  1142. metadataNet.metadata = [CCCoreData insertEntityInMetadata:recordMetadata];
  1143. metadataNet.downloadData = NO;
  1144. metadataNet.downloadPlist = YES;
  1145. metadataNet.selector = selectorLoadPlist;
  1146. metadataNet.serverUrl = serverUrl;
  1147. metadataNet.session = k_download_session_foreground;
  1148. metadataNet.taskStatus = k_taskStatusResume;
  1149. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1150. }
  1151. }
  1152. }
  1153. #pragma --------------------------------------------------------------------------------------------
  1154. #pragma mark ===== Upload new Photos/Videos =====
  1155. #pragma --------------------------------------------------------------------------------------------
  1156. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1157. {
  1158. // Automatic upload All
  1159. if([selector isEqualToString:selectorUploadAutomaticAll])
  1160. [app performSelectorOnMainThread:@selector(loadAutomaticUpload) withObject:nil waitUntilDone:NO];
  1161. // Read File test do not exists
  1162. if (errorCode == k_CCErrorFileUploadNotFound && fileID) {
  1163. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  1164. // reUpload
  1165. if (metadata)
  1166. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1167. }
  1168. // Print error
  1169. else if (errorCode != kCFURLErrorCancelled && errorCode != 403) {
  1170. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1171. }
  1172. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1173. }
  1174. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1175. {
  1176. // Automatic upload All
  1177. if([selector isEqualToString:selectorUploadAutomaticAll])
  1178. [app performSelectorOnMainThread:@selector(loadAutomaticUpload) withObject:nil waitUntilDone:NO];
  1179. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1180. [self readFolderWithForced:YES serverUrl:serverUrl];
  1181. } else {
  1182. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1183. }
  1184. }
  1185. //
  1186. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1187. //
  1188. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1189. {
  1190. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1191. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:cryptated], [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1192. });
  1193. }
  1194. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1195. {
  1196. NSArray *assets = [arguments objectAtIndex:0];
  1197. NSString *serverUrl = [arguments objectAtIndex:1];
  1198. BOOL cryptated = [[arguments objectAtIndex:2] boolValue];
  1199. BOOL useSubFolder = [[arguments objectAtIndex:3] boolValue];
  1200. NSString *session = [arguments objectAtIndex:4];
  1201. NSString *folderPhotos = [CCCoreData getCameraUploadFolderNamePathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  1202. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:app.activeAccount];
  1203. // Create the folder for Photos & if request the subfolders
  1204. if (![app createFolderSubFolderAutomaticUploadFolderPhotos:folderPhotos useSubFolder:useSubFolder assets:assets selector:selectorUploadFile])
  1205. return;
  1206. NSLog(@"[LOG] Asset N. %lu", (unsigned long)[assets count]);
  1207. for (PHAsset *asset in assets) {
  1208. NSString *fileName = [CCUtility createFileNameFromAsset:asset key: k_keyFileNameMask];
  1209. NSDate *assetDate = asset.creationDate;
  1210. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1211. // Create serverUrl if use sub folder
  1212. if (useSubFolder) {
  1213. [formatter setDateFormat:@"yyyy"];
  1214. NSString *yearString = [formatter stringFromDate:assetDate];
  1215. [formatter setDateFormat:@"MM"];
  1216. NSString *monthString = [formatter stringFromDate:assetDate];
  1217. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", folderPhotos, yearString, monthString];
  1218. }
  1219. // Check if is in upload
  1220. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (fileName == %@) AND (session != NULL) AND (session != '')", app.activeAccount, directoryID, fileName];
  1221. NSArray *isRecordInSessions = [CCCoreData getTableMetadataWithPredicate:predicate context:nil];
  1222. if ([isRecordInSessions count] > 0) {
  1223. // next upload
  1224. continue;
  1225. } else {
  1226. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1227. metadataNet.action = actionReadFile;
  1228. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1229. metadataNet.cryptated = cryptated;
  1230. metadataNet.fileName = fileName;
  1231. metadataNet.priority = NSOperationQueuePriorityNormal;
  1232. metadataNet.session = session;
  1233. metadataNet.selector = selectorReadFileUploadFile;
  1234. metadataNet.serverUrl = serverUrl;
  1235. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1236. }
  1237. }
  1238. }
  1239. #pragma --------------------------------------------------------------------------------------------
  1240. #pragma mark ==== Read File ====
  1241. #pragma --------------------------------------------------------------------------------------------
  1242. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1243. {
  1244. // UploadFile
  1245. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1246. // File not exists
  1247. if (errorCode == 404) {
  1248. metadataNet.action = actionUploadAsset;
  1249. metadataNet.errorCode = 0;
  1250. metadataNet.selector = selectorUploadFile;
  1251. metadataNet.selectorPost = nil;
  1252. metadataNet.taskStatus = k_taskStatusResume;
  1253. if ([metadataNet.session containsString:@"wwan"])
  1254. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1255. else
  1256. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1257. } else {
  1258. // error ho many retry befor notification and go to on next asses
  1259. if (metadataNet.errorRetry < 3) {
  1260. // Retry read file
  1261. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1262. } else {
  1263. // STOP check file, view message error
  1264. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1265. }
  1266. }
  1267. }
  1268. }
  1269. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(CCMetadata *)metadata
  1270. {
  1271. // UploadFile
  1272. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1273. metadataNet.action = actionUploadAsset;
  1274. metadataNet.errorCode = 403; // File exists 403 Forbidden
  1275. metadataNet.selector = selectorUploadFile;
  1276. metadataNet.selectorPost = nil;
  1277. metadataNet.taskStatus = k_taskStatusResume;
  1278. if ([metadataNet.session containsString:@"wwan"])
  1279. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1280. else
  1281. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1282. }
  1283. }
  1284. #pragma --------------------------------------------------------------------------------------------
  1285. #pragma mark ==== Read Folder ====
  1286. #pragma --------------------------------------------------------------------------------------------
  1287. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1288. {
  1289. // verify active user
  1290. TableAccount *record = [CCCoreData getActiveAccount];
  1291. [_hud hideHud];
  1292. [_refreshControl endRefreshing];
  1293. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1294. if (message && [record.account isEqualToString:metadataNet.account])
  1295. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1296. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1297. if (errorCode == 401)
  1298. [self changePasswordAccount];
  1299. }
  1300. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet permissions:(NSString *)permissions etag:(NSString *)etag metadatas:(NSArray *)metadatas
  1301. {
  1302. // verify active user
  1303. TableAccount *record = [CCCoreData getActiveAccount];
  1304. if (![record.account isEqualToString:metadataNet.account])
  1305. return;
  1306. // save father e update permission
  1307. if(!_isSearchMode)
  1308. _fatherPermission = permissions;
  1309. NSArray *recordsInSessions;
  1310. if (_isSearchMode) {
  1311. recordsInSessions = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (session != NULL) AND (session != '')", metadataNet.account] context:nil];
  1312. } else {
  1313. [CCCoreData updateDirectoryEtagServerUrl:metadataNet.serverUrl etag:etag activeAccount:metadataNet.account];
  1314. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND ((session == NULL) OR (session == ''))", metadataNet.account, metadataNet.directoryID]];
  1315. recordsInSessions = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (session != NULL) AND (session != '')", metadataNet.account, metadataNet.directoryID] context:nil];
  1316. [CCCoreData setDateReadDirectoryID:metadataNet.directoryID activeAccount:app.activeAccount];
  1317. }
  1318. for (CCMetadata *metadata in metadatas) {
  1319. // Delete Record only in Search Mode
  1320. if (_isSearchMode)
  1321. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (fileID = %@) AND ((session == NULL) OR (session == ''))", metadataNet.account, metadata.directoryID, metadata.fileID]];
  1322. // type of file
  1323. NSInteger typeFilename = [CCUtility getTypeFileName:metadata.fileName];
  1324. // if crypto do not insert
  1325. if (typeFilename == k_metadataTypeFilenameCrypto) continue;
  1326. // verify if the record encrypted has plist + crypto
  1327. if (typeFilename == k_metadataTypeFilenamePlist && metadata.directory == NO) {
  1328. BOOL isCryptoComplete = NO;
  1329. NSString *fileNameCrypto = [CCUtility trasformedFileNamePlistInCrypto:metadata.fileName];
  1330. for (CCMetadata *completeMetadata in metadatas) {
  1331. if (completeMetadata.cryptated == NO) continue;
  1332. else if ([completeMetadata.fileName isEqualToString:fileNameCrypto]) {
  1333. isCryptoComplete = YES;
  1334. break;
  1335. }
  1336. }
  1337. if (isCryptoComplete == NO) continue;
  1338. }
  1339. // verify if the record is in download/upload progress
  1340. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1341. CCMetadata *metadataDB = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (fileName == %@)", app.activeAccount, metadataNet.directoryID, metadata.fileName] context:nil];
  1342. // is in Upload
  1343. if (metadataDB.session && [metadataDB.session containsString:@"upload"]) {
  1344. NSString *sessionID = metadataDB.sessionID;
  1345. // rename SessionID -> fileID
  1346. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, sessionID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]];
  1347. metadataDB.session = @"";
  1348. metadataDB.date = metadata.date;
  1349. metadataDB.fileID = metadata.fileID;
  1350. metadataDB.rev = metadata.fileID;
  1351. metadataDB.sessionError = @"";
  1352. metadataDB.sessionID = @"";
  1353. metadataDB.sessionTaskIdentifier = k_taskIdentifierDone;
  1354. metadataDB.sessionTaskIdentifierPlist = k_taskIdentifierDone;
  1355. [CCCoreData updateMetadata:metadataDB predicate:[NSPredicate predicateWithFormat:@"(sessionID == %@) AND (account == %@)", sessionID, app.activeAccount] activeAccount:app.activeAccount activeUrl:app.activeUrl context:nil];
  1356. [CCCoreData addLocalFile:metadataDB activeAccount:app.activeAccount];
  1357. [CCGraphics createNewImageFrom:metadata.fileID directoryUser:app.directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:NO typeFile:metadata.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  1358. continue;
  1359. }
  1360. // download in progress
  1361. if (metadataDB.session && [metadataDB.session containsString:@"download"])
  1362. continue;
  1363. }
  1364. // end test, insert in CoreData
  1365. [CCCoreData addMetadata:metadata activeAccount:app.activeAccount activeUrl:app.activeUrl context:nil];
  1366. }
  1367. // read plist
  1368. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1369. // File is changed ??
  1370. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1371. if (!_isSearchMode)
  1372. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatas serverUrl:metadataNet.serverUrl account:app.activeAccount withDownload:NO];
  1373. });
  1374. // Search Mode
  1375. if (_isSearchMode)
  1376. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1377. // this is the same directory
  1378. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1379. // reload
  1380. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1381. // stoprefresh
  1382. [_refreshControl endRefreshing];
  1383. // Enable change user
  1384. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1385. [_hud hideHud];
  1386. }
  1387. }
  1388. - (void)readFolderWithForced:(BOOL)forced serverUrl:(NSString *)serverUrl
  1389. {
  1390. // init control
  1391. if (!serverUrl || !app.activeAccount)
  1392. return;
  1393. // Search Mode
  1394. if (_isSearchMode) {
  1395. if (forced) {
  1396. [CCCoreData clearDateReadAccount:app.activeAccount serverUrl:serverUrl directoryID:nil];
  1397. _searchFileName = @""; // forced reload searchg
  1398. }
  1399. [self updateSearchResultsForSearchController:self.searchController];
  1400. return;
  1401. }
  1402. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:app.activeAccount];
  1403. if ([CCCoreData isDirectoryOutOfDate:k_dayForceReadFolder directoryID:directoryID activeAccount:app.activeAccount] || forced) {
  1404. if (_refreshControl.isRefreshing == NO)
  1405. [_hud visibleIndeterminateHud];
  1406. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1407. metadataNet.action = actionReadFolder;
  1408. metadataNet.date = [NSDate date];
  1409. metadataNet.directoryID = directoryID;
  1410. metadataNet.priority = NSOperationQueuePriorityHigh;
  1411. metadataNet.selector = selectorReadFolder;
  1412. metadataNet.serverUrl = serverUrl;
  1413. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1414. }
  1415. }
  1416. #pragma mark -
  1417. #pragma --------------------------------------------------------------------------------------------
  1418. #pragma mark ===== Search =====
  1419. #pragma --------------------------------------------------------------------------------------------
  1420. -(void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1421. {
  1422. _isSearchMode = YES;
  1423. [self deleteRefreshControl];
  1424. NSString *fileName = [CCUtility removeForbiddenCharacters:searchController.searchBar.text hasServerForbiddenCharactersSupport:app.hasServerForbiddenCharactersSupport];
  1425. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1426. _searchFileName = fileName;
  1427. if (app.serverVersion >= 12 && ![_depth isEqualToString:@"0"]) {
  1428. [[CCActions sharedInstance] search:_serverUrl fileName:_searchFileName depth:_depth delegate:self];
  1429. _noFilesSearchTitle = @"";
  1430. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1431. [self.tableView reloadEmptyDataSet];
  1432. } else {
  1433. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount];
  1434. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(directoryID == %@) AND (account == %@) AND (fileNamePrint CONTAINS[cd] %@)", directoryID, app.activeAccount, fileName];
  1435. NSArray *records = [CCCoreData getTableMetadataWithPredicate:predicate context:nil];
  1436. [_searchResultMetadatas removeAllObjects];
  1437. for (TableMetadata *record in records)
  1438. [_searchResultMetadatas addObject:[CCCoreData insertEntityInMetadata:record]];
  1439. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1440. metadataNet.account = app.activeAccount;
  1441. metadataNet.action = actionUploadTemplate;
  1442. metadataNet.directoryID = directoryID;
  1443. metadataNet.selector = selectorSearch;
  1444. metadataNet.serverUrl = _serverUrl;
  1445. [self readFolderSuccess:metadataNet permissions:@"" etag:@"" metadatas:_searchResultMetadatas];
  1446. }
  1447. }
  1448. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1449. [self reloadDatasource];
  1450. }
  1451. }
  1452. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1453. {
  1454. [self cancelSearchBar];
  1455. [self readFolderWithForced:NO serverUrl:_serverUrl];
  1456. }
  1457. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1458. {
  1459. _searchFileName = @"";
  1460. if (message)
  1461. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1462. }
  1463. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1464. {
  1465. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1466. [self readFolderSuccess:metadataNet permissions:nil etag:nil metadatas:metadatas];
  1467. }
  1468. - (void)cancelSearchBar
  1469. {
  1470. if (self.searchController.active) {
  1471. [self.searchController setActive:NO];
  1472. [self createRefreshControl];
  1473. _isSearchMode = NO;
  1474. _searchFileName = @"";
  1475. _dateReadDataSource = nil;
  1476. _searchResultMetadatas = [NSMutableArray new];
  1477. [self reloadDatasource];
  1478. }
  1479. }
  1480. - (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope
  1481. {
  1482. NSString *title = [self.searchController.searchBar.scopeButtonTitles objectAtIndex:selectedScope];
  1483. self.searchController.searchBar.placeholder = title;
  1484. if ([title isEqualToString:NSLocalizedString(@"_search_this_folder_",nil)])
  1485. _depth = @"0";
  1486. if ([title isEqualToString:NSLocalizedString(@"_search_sub_folder_",nil)])
  1487. _depth = @"1";
  1488. if ([title isEqualToString:NSLocalizedString(@"_search_all_folders_",nil)])
  1489. _depth = @"infinity";
  1490. _searchFileName = @"";
  1491. [self updateSearchResultsForSearchController:self.searchController];
  1492. }
  1493. #pragma mark -
  1494. #pragma --------------------------------------------------------------------------------------------
  1495. #pragma mark ===== Delete File or Folder =====
  1496. #pragma --------------------------------------------------------------------------------------------
  1497. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1498. {
  1499. [self deleteFileOrFolderSuccess:metadataNet];
  1500. }
  1501. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1502. {
  1503. [_queueSelector removeObject:metadataNet.selector];
  1504. if ([_queueSelector count] == 0) {
  1505. [_hud hideHud];
  1506. if (_isSearchMode)
  1507. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1508. else
  1509. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.metadata.fileID selector:metadataNet.selector];
  1510. // next
  1511. if ([_selectedMetadatas count] > 0) {
  1512. [_selectedMetadatas removeObjectAtIndex:0];
  1513. if ([_selectedMetadatas count] > 0)
  1514. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1515. }
  1516. }
  1517. }
  1518. - (void)deleteFileOrFolder:(CCMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1519. {
  1520. if (metadata.cryptated) {
  1521. [_queueSelector addObject:selectorDeleteCrypto];
  1522. [_queueSelector addObject:selectorDeletePlist];
  1523. } else {
  1524. [_queueSelector addObject:selectorDelete];
  1525. }
  1526. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1527. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1528. }
  1529. - (void)deleteSelectionFile
  1530. {
  1531. [_selectedMetadatas removeAllObjects];
  1532. [_queueSelector removeAllObjects];
  1533. _selectedMetadatas = [[NSMutableArray alloc] initWithArray: [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]]];
  1534. _numSelectedMetadatas = [_selectedMetadatas count];
  1535. if ([_selectedMetadatas count] > 0)
  1536. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1537. [self tableViewSelect:NO];
  1538. }
  1539. - (void)deleteFile
  1540. {
  1541. [_selectedMetadatas removeAllObjects];
  1542. [_queueSelector removeAllObjects];
  1543. _numSelectedMetadatas = 1;
  1544. [_selectedMetadatas addObject:_metadata];
  1545. if ([_selectedMetadatas count] > 0)
  1546. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1547. [self tableViewSelect:NO];
  1548. }
  1549. #pragma --------------------------------------------------------------------------------------------
  1550. #pragma mark ===== Rename / Move =====
  1551. #pragma --------------------------------------------------------------------------------------------
  1552. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1553. {
  1554. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1555. }
  1556. - (void)renameFile:(CCMetadata *)metadata fileName:(NSString *)fileName
  1557. {
  1558. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1559. }
  1560. - (void)renameNote:(CCMetadata *)metadata fileName:(NSString *)fileName
  1561. {
  1562. CCTemplates *templates = [[CCTemplates alloc] init];
  1563. NSMutableDictionary *field = [[CCCrypto sharedManager] getDictionaryEncrypted:metadata.fileName uuid:metadata.uuid isLocal:NO directoryUser:app.directoryUser];
  1564. NSString *fileNameModel = [templates salvaNote:[field objectForKey:@"note"] titolo:fileName fileName:metadata.fileName uuid:metadata.uuid];
  1565. if (fileNameModel) {
  1566. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1567. metadataNet.action = actionUploadTemplate;
  1568. metadataNet.fileName = [CCUtility trasformedFileNamePlistInCrypto:fileNameModel];
  1569. metadataNet.fileNamePrint = fileName;
  1570. metadataNet.rev = metadata.rev;
  1571. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1572. metadataNet.session = k_upload_session_foreground;
  1573. metadataNet.taskStatus = k_taskStatusResume;
  1574. if ([CCCoreData isOfflineLocalFileID:metadata.fileID activeAccount:app.activeAccount])
  1575. metadataNet.selectorPost = selectorAddOffline;
  1576. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1577. }
  1578. }
  1579. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1580. {
  1581. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1582. [_hud hideHud];
  1583. if (message)
  1584. [app messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1585. [_selectedMetadatas removeAllObjects];
  1586. [_queueSelector removeAllObjects];
  1587. }
  1588. }
  1589. - (void)moveSuccess:(CCMetadataNet *)metadataNet revTo:(NSString *)revTo
  1590. {
  1591. [_queueSelector removeObject:metadataNet.selector];
  1592. if ([_queueSelector count] == 0) {
  1593. [_hud hideHud];
  1594. NSString *fileName = [CCUtility trasformedFileNameCryptoInPlist:metadataNet.fileName];
  1595. NSString *directoryID = metadataNet.directoryID;
  1596. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1597. NSString *serverUrlTo = [CCCoreData getServerUrlFromDirectoryID:directoryIDTo activeAccount:app.activeAccount];
  1598. // FILE -> Metadata
  1599. if (metadataNet.directory == NO) {
  1600. // move metadata
  1601. [CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1602. }
  1603. // DIRECTORY -> Directory - CCMetadata
  1604. if (metadataNet.directory == YES) {
  1605. // delete all dir / subdir
  1606. NSArray *directoryIDs = [CCCoreData deleteDirectoryAndSubDirectory:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName] activeAccount:app.activeAccount];
  1607. // delete all metadata and local file in dir / subdir
  1608. for (NSString *directoryIDDelete in directoryIDs)
  1609. [CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(directoryID == %@)AND (account == %@)",directoryIDDelete, app.activeAccount]];
  1610. // move metadata
  1611. [CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1612. // Add new directory
  1613. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1614. [CCCoreData addDirectory:newDirectory permissions:nil activeAccount:app.activeAccount];
  1615. // Check Offline
  1616. if ([CCCoreData isOfflineDirectoryServerUrl:serverUrlTo activeAccount:app.activeAccount])
  1617. [CCCoreData setOfflineDirectoryServerUrl:newDirectory offline:YES activeAccount:app.activeAccount];
  1618. }
  1619. // reload Datasource
  1620. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1621. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1622. else
  1623. [self reloadDatasource];
  1624. // Next file
  1625. [_selectedMetadatas removeObjectAtIndex:0];
  1626. [self performSelectorOnMainThread:@selector(moveFileOrFolder:) withObject:metadataNet.serverUrlTo waitUntilDone:NO];
  1627. }
  1628. }
  1629. - (void)moveFileOrFolder:(NSString *)serverUrlTo
  1630. {
  1631. if ([_selectedMetadatas count] > 0) {
  1632. CCMetadata *metadata = [_selectedMetadatas objectAtIndex:0];
  1633. // Plain
  1634. if (metadata.cryptated == NO) {
  1635. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withPassword:app.activePassword withUrl:app.activeUrl isCryptoCloudMode:NO];
  1636. NSError *error = [ocNetworking readFileSync:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName]];
  1637. if(!error) {
  1638. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1639. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1640. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1641. }];
  1642. [alert addAction:ok];
  1643. [self presentViewController:alert animated:YES completion:nil];
  1644. });
  1645. return;
  1646. }
  1647. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1648. metadataNet.action = actionMoveFileOrFolder;
  1649. metadataNet.directory = metadata.directory;
  1650. metadataNet.fileID = metadata.fileID;
  1651. metadataNet.directoryID = metadata.directoryID;
  1652. metadataNet.directoryIDTo = [CCCoreData getDirectoryIDFromServerUrl:serverUrlTo activeAccount:app.activeAccount];
  1653. metadataNet.fileName = metadata.fileName;
  1654. metadataNet.fileNamePrint = metadataNet.fileNamePrint;
  1655. metadataNet.fileNameTo = metadata.fileName;
  1656. metadataNet.rev = metadata.rev;
  1657. metadataNet.selector = selectorMove;
  1658. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1659. metadataNet.serverUrlTo = serverUrlTo;
  1660. [_queueSelector addObject:metadataNet.selector];
  1661. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1662. }
  1663. // cyptated
  1664. if (metadata.cryptated == YES) {
  1665. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1666. metadataNet.action = actionMoveFileOrFolder;
  1667. metadataNet.directory = metadata.directory;
  1668. metadataNet.fileID = metadata.fileID;
  1669. metadataNet.directoryID = metadata.directoryID;
  1670. metadataNet.directoryIDTo = [CCCoreData getDirectoryIDFromServerUrl:serverUrlTo activeAccount:app.activeAccount];
  1671. metadataNet.fileNamePrint = metadata.fileNamePrint;
  1672. metadataNet.rev = metadata.rev;
  1673. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1674. metadataNet.serverUrlTo = serverUrlTo;
  1675. // data
  1676. metadataNet.fileName = metadata.fileNameData;
  1677. metadataNet.fileNameTo = metadata.fileNameData;
  1678. metadataNet.selector = selectorMoveCrypto;
  1679. [_queueSelector addObject:metadataNet.selector];
  1680. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1681. // plist
  1682. metadataNet.fileName = metadata.fileName;
  1683. metadataNet.fileNameTo = metadata.fileName;
  1684. metadataNet.selector = selectorMovePlist;
  1685. [_queueSelector addObject:metadataNet.selector];
  1686. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1687. }
  1688. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), _numSelectedMetadatas - [_selectedMetadatas count] + 1, _numSelectedMetadatas] mode:MBProgressHUDModeIndeterminate color:nil];
  1689. }
  1690. }
  1691. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title selectedMetadatas:(NSArray *)selectedMetadatas
  1692. {
  1693. [_selectedMetadatas removeAllObjects];
  1694. [_queueSelector removeAllObjects];
  1695. _selectedMetadatas = [[NSMutableArray alloc] initWithArray:selectedMetadatas];
  1696. _numSelectedMetadatas = [_selectedMetadatas count];
  1697. [self performSelectorOnMainThread:@selector(moveFileOrFolder:) withObject:serverUrlTo waitUntilDone:NO];
  1698. [self tableViewSelect:NO];
  1699. }
  1700. - (void)moveOpenWindow:(NSArray *)indexPaths
  1701. {
  1702. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1703. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1704. viewController.delegate = self;
  1705. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1706. viewController.selectedMetadatas = [self getMetadatasFromSelectedRows:indexPaths];
  1707. viewController.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  1708. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1709. viewController.tintColorTitle = [NCBrandColor sharedInstance].navigationBarText;
  1710. viewController.networkingOperationQueue = app.netQueue;
  1711. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1712. [self presentViewController:navigationController animated:YES completion:nil];
  1713. }
  1714. #pragma --------------------------------------------------------------------------------------------
  1715. #pragma mark ===== Create folder =====
  1716. #pragma --------------------------------------------------------------------------------------------
  1717. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1718. {
  1719. [_hud hideHud];
  1720. if (message)
  1721. [app messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1722. }
  1723. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1724. {
  1725. [_hud hideHud];
  1726. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1727. [CCCoreData addDirectory:newDirectory permissions:nil activeAccount:app.activeAccount];
  1728. // Check Offline
  1729. if ([CCCoreData isOfflineDirectoryServerUrl:_serverUrl activeAccount:app.activeAccount])
  1730. [CCCoreData setOfflineDirectoryServerUrl:newDirectory offline:YES activeAccount:app.activeAccount];
  1731. // Load Folder or the Datasource
  1732. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced]) {
  1733. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1734. } else {
  1735. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  1736. }
  1737. }
  1738. - (void)createFolder:(NSString *)fileNameFolder folderCameraUpload:(BOOL)folderCameraUpload
  1739. {
  1740. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1741. fileNameFolder = [CCUtility removeForbiddenCharacters:fileNameFolder hasServerForbiddenCharactersSupport:app.hasServerForbiddenCharactersSupport];
  1742. if (![fileNameFolder length]) return;
  1743. if (folderCameraUpload) metadataNet.serverUrl = [CCCoreData getCameraUploadFolderPathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  1744. else metadataNet.serverUrl = _serverUrl;
  1745. metadataNet.action = actionCreateFolder;
  1746. if (folderCameraUpload)
  1747. metadataNet.options = @"folderCameraUpload";
  1748. metadataNet.fileName = fileNameFolder;
  1749. metadataNet.selector = selectorCreateFolder;
  1750. metadataNet.selectorPost = selectorReadFolderForced;
  1751. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1752. if (!folderCameraUpload)
  1753. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1754. }
  1755. - (void)createFolderEncrypted:(NSString *)fileNameFolder
  1756. {
  1757. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1758. NSString *fileNamePlist;
  1759. fileNameFolder = [CCUtility removeForbiddenCharacters:fileNameFolder hasServerForbiddenCharactersSupport:app.hasServerForbiddenCharactersSupport];
  1760. if (![fileNameFolder length]) return;
  1761. NSString *title = [AESCrypt encrypt:fileNameFolder password:[[CCCrypto sharedManager] getKeyPasscode:[CCUtility getUUID]]];
  1762. fileNamePlist = [[CCCrypto sharedManager] createFilenameEncryptor:fileNameFolder uuid:[CCUtility getUUID]];
  1763. [[CCCrypto sharedManager] createFilePlist:[NSTemporaryDirectory() stringByAppendingString:fileNamePlist] title:title len:0 directory:true uuid:[CCUtility getUUID] nameCurrentDevice:[CCUtility getNameCurrentDevice] icon:@""];
  1764. // Create folder
  1765. metadataNet.action = actionCreateFolder;
  1766. metadataNet.fileName = fileNamePlist;
  1767. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1768. metadataNet.selector = selectorCreateFolder;
  1769. metadataNet.serverUrl = _serverUrl;
  1770. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1771. // upload plist file
  1772. metadataNet.action = actionUploadOnlyPlist;
  1773. metadataNet.fileName = [fileNamePlist stringByAppendingString:@".plist"];
  1774. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1775. metadataNet.selectorPost = selectorReadFolderForced;
  1776. metadataNet.serverUrl = _serverUrl;
  1777. metadataNet.session = k_upload_session_foreground;
  1778. metadataNet.taskStatus = k_taskStatusResume;
  1779. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1780. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1781. }
  1782. - (void)createFolderCameraUpload
  1783. {
  1784. [self createFolder:[CCCoreData getCameraUploadFolderNameActiveAccount:app.activeAccount] folderCameraUpload:YES];
  1785. }
  1786. #pragma --------------------------------------------------------------------------------------------
  1787. #pragma mark ===== Encrypted / Decrypted Folder =====
  1788. #pragma --------------------------------------------------------------------------------------------
  1789. - (void)encyptedDecryptedFolder
  1790. {
  1791. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  1792. if (_metadata.cryptated) {
  1793. // DECRYPTED
  1794. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1795. //-------------------------- RENAME -------------------------------------------//
  1796. metadataNet.action = actionMoveFileOrFolder;
  1797. metadataNet.fileID = _metadata.fileID;
  1798. metadataNet.fileName = _metadata.fileNameData;
  1799. metadataNet.fileNameTo = _metadata.fileNamePrint;
  1800. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1801. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1802. metadataNet.selector = selectorRename;
  1803. metadataNet.serverUrl = serverUrl;
  1804. metadataNet.serverUrlTo = serverUrl;
  1805. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1806. //-------------------------- DELETE -------------------------------------------//
  1807. metadataNet.action = actionDeleteFileDirectory;
  1808. metadataNet.fileID = _metadata.fileID;
  1809. metadataNet.fileName = _metadata.fileName;
  1810. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1811. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1812. metadataNet.selector = selectorDeletePlist;
  1813. metadataNet.selectorPost = selectorReadFolderForced;
  1814. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1815. } else {
  1816. // ENCRYPTED
  1817. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1818. // Create File Plist
  1819. NSString *fileNameCrypto = [[CCCrypto sharedManager] createFileDirectoryPlist:_metadata];
  1820. //-------------------------- RENAME -------------------------------------------//
  1821. metadataNet.action = actionMoveFileOrFolder;
  1822. metadataNet.fileID = _metadata.fileID;
  1823. metadataNet.fileName = _metadata.fileName;
  1824. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1825. metadataNet.fileNameTo = fileNameCrypto;
  1826. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1827. metadataNet.selector = selectorRename;
  1828. metadataNet.serverUrl = serverUrl;
  1829. metadataNet.serverUrlTo = serverUrl;
  1830. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1831. //-------------------------- UPLOAD -------------------------------------------//
  1832. metadataNet.action = actionUploadOnlyPlist;
  1833. metadataNet.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  1834. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1835. metadataNet.selectorPost = selectorReadFolderForced;
  1836. metadataNet.serverUrl = serverUrl;
  1837. metadataNet.session = k_upload_session_foreground;
  1838. metadataNet.taskStatus = k_taskStatusResume;
  1839. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1840. }
  1841. }
  1842. #pragma --------------------------------------------------------------------------------------------
  1843. #pragma mark ===== Encrypted/Decrypted File =====
  1844. #pragma --------------------------------------------------------------------------------------------
  1845. - (void)encryptedSelectedFiles
  1846. {
  1847. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1848. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1849. for (CCMetadata *metadata in selectedMetadatas) {
  1850. if (metadata.cryptated == NO && metadata.directory == NO)
  1851. [metadatas addObject:metadata];
  1852. }
  1853. if ([metadatas count] > 0) {
  1854. NSLog(@"[LOG] Start encrypted selected files ...");
  1855. for (CCMetadata* metadata in metadatas) {
  1856. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1857. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorEncryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1858. }
  1859. }
  1860. [self tableViewSelect:NO];
  1861. }
  1862. - (void)decryptedSelectedFiles
  1863. {
  1864. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1865. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1866. for (CCMetadata *metadata in selectedMetadatas) {
  1867. if (metadata.cryptated == YES && metadata.directory == NO && [metadata.model length] == 0)
  1868. [metadatas addObject:metadata];
  1869. }
  1870. if ([metadatas count] > 0) {
  1871. NSLog(@"[LOG] Start decrypted selected files ...");
  1872. for (CCMetadata* metadata in metadatas) {
  1873. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1874. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDecryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1875. }
  1876. }
  1877. [self tableViewSelect:NO];
  1878. }
  1879. - (void)cmdEncryptedDecryptedFile
  1880. {
  1881. NSString *selector;
  1882. if (_metadata.cryptated == YES) selector = selectorDecryptFile;
  1883. if (_metadata.cryptated == NO) selector = selectorEncryptFile;
  1884. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  1885. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  1886. }
  1887. - (void)encryptedFile:(CCMetadata *)metadata
  1888. {
  1889. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1890. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1891. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1892. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1893. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:app.activeAccount];
  1894. dispatch_async(dispatch_get_main_queue(), ^{
  1895. [[CCNetworking sharedNetworking] uploadFile:metadata.fileName serverUrl:serverUrl cryptated:YES onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1896. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1897. });
  1898. } else {
  1899. [app messageNotification:@"_encrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1900. }
  1901. }
  1902. - (void)decryptedFile:(CCMetadata *)metadata
  1903. {
  1904. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1905. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1906. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1907. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1908. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:app.activeAccount];
  1909. dispatch_async(dispatch_get_main_queue(), ^{
  1910. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:serverUrl cryptated:NO onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1911. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1912. });
  1913. } else {
  1914. [app messageNotification:@"_decrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  1915. }
  1916. }
  1917. #pragma --------------------------------------------------------------------------------------------
  1918. #pragma mark ===== Progress & Task Button =====
  1919. #pragma --------------------------------------------------------------------------------------------
  1920. - (void)triggerProgressTask:(NSNotification *)notification
  1921. {
  1922. NSDictionary *dict = notification.userInfo;
  1923. NSString *fileID = [dict valueForKey:@"fileID"];
  1924. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1925. BOOL cryptated = [[dict valueForKey:@"cryptated"] boolValue];
  1926. float progress = [[dict valueForKey:@"progress"] floatValue];
  1927. // Check
  1928. if (!fileID)
  1929. return;
  1930. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1931. if (![serverUrl isEqualToString:_serverUrl])
  1932. return;
  1933. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1934. if (indexPath) {
  1935. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1936. if (cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  1937. else cell.progressView.progressTintColor = [UIColor blackColor];
  1938. cell.progressView.hidden = NO;
  1939. [cell.progressView setProgress:progress];
  1940. }
  1941. if (progress == 0)
  1942. [self.navigationController cancelCCProgress];
  1943. else
  1944. [self.navigationController setCCProgressPercentage:progress*100 andTintColor: [NCBrandColor sharedInstance].navigationBarProgress];
  1945. }
  1946. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  1947. {
  1948. UITouch * touch = [[event allTouches] anyObject];
  1949. CGPoint location = [touch locationInView:self.tableView];
  1950. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  1951. if (indexPath) {
  1952. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1953. if (metadata)
  1954. [self reloadTaskButton:metadata];
  1955. }
  1956. }
  1957. - (void)reloadTaskButton:(CCMetadata *)metadata
  1958. {
  1959. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1960. __block NSURLSessionTask *findTask;
  1961. // DOWNLOAD
  1962. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1963. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1964. for (NSURLSessionUploadTask *task in downloadTasks)
  1965. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  1966. findTask = task;
  1967. [app.listChangeTask setObject:@"reloadDownload" forKey:metadata.fileID];
  1968. [task cancel];
  1969. }
  1970. if (!findTask) {
  1971. dispatch_async(dispatch_get_main_queue(), ^{
  1972. [app.listChangeTask setObject:@"reloadDownload" forKey:metadata.fileID];
  1973. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  1974. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  1975. });
  1976. }
  1977. }];
  1978. }
  1979. // UPLOAD
  1980. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1981. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1982. for (NSURLSessionUploadTask *task in uploadTasks)
  1983. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  1984. findTask = task;
  1985. [app.listChangeTask setObject:@"reloadUpload" forKey:metadata.fileID];
  1986. [task cancel];
  1987. }
  1988. if (!findTask) {
  1989. dispatch_async(dispatch_get_main_queue(), ^{
  1990. [app.listChangeTask setObject:@"reloadUpload" forKey:metadata.fileID];
  1991. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  1992. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  1993. });
  1994. }
  1995. }];
  1996. }
  1997. }
  1998. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1999. {
  2000. UITouch * touch = [[event allTouches] anyObject];
  2001. CGPoint location = [touch locationInView:self.tableView];
  2002. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2003. if (indexPath) {
  2004. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2005. if (metadata)
  2006. [self cancelTaskButton:metadata reloadTable:YES];
  2007. }
  2008. }
  2009. - (void)cancelTaskButton:(CCMetadata *)metadata reloadTable:(BOOL)reloadTable
  2010. {
  2011. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2012. __block NSURLSessionTask *findTask;
  2013. // DOWNLOAD
  2014. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  2015. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2016. for (NSURLSessionTask *task in downloadTasks)
  2017. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  2018. findTask = task;
  2019. [app.listChangeTask setObject:@"cancelDownload" forKey:metadata.fileID];
  2020. [task cancel];
  2021. }
  2022. if (!findTask) {
  2023. [app.listChangeTask setObject:@"cancelDownload" forKey:metadata.fileID];
  2024. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  2025. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2026. }
  2027. }];
  2028. }
  2029. // UPLOAD
  2030. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2031. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2032. for (NSURLSessionUploadTask *task in uploadTasks)
  2033. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  2034. findTask = task;
  2035. [app.listChangeTask setObject:@"cancelUpload" forKey:metadata.fileID];
  2036. [task cancel];
  2037. }
  2038. if (!findTask) {
  2039. dispatch_async(dispatch_get_main_queue(), ^{
  2040. [app.listChangeTask setObject:@"cancelUpload" forKey:metadata.fileID];
  2041. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  2042. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2043. });
  2044. }
  2045. }];
  2046. }
  2047. }
  2048. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  2049. {
  2050. UITouch * touch = [[event allTouches] anyObject];
  2051. CGPoint location = [touch locationInView:self.tableView];
  2052. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2053. if (indexPath) {
  2054. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2055. if (metadata)
  2056. [self stopTaskButton:metadata];
  2057. }
  2058. }
  2059. - (void)stopTaskButton:(CCMetadata *)metadata
  2060. {
  2061. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2062. __block NSURLSessionTask *findTask;
  2063. // UPLOAD
  2064. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2065. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2066. for (NSURLSessionUploadTask *task in uploadTasks)
  2067. if (task.taskIdentifier == metadata.sessionTaskIdentifier || task.taskIdentifier == metadata.sessionTaskIdentifierPlist) {
  2068. [app.listChangeTask setObject:@"stopUpload" forKey:metadata.fileID];
  2069. findTask = task;
  2070. [task cancel];
  2071. }
  2072. if (!findTask) {
  2073. dispatch_async(dispatch_get_main_queue(), ^{
  2074. [app.listChangeTask setObject:@"stopUpload" forKey:metadata.fileID];
  2075. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  2076. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2077. });
  2078. }
  2079. }];
  2080. }
  2081. }
  2082. #pragma --------------------------------------------------------------------------------------------
  2083. #pragma mark ===== Shared =====
  2084. #pragma --------------------------------------------------------------------------------------------
  2085. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  2086. {
  2087. [_hud hideHud];
  2088. // change account ?
  2089. TableAccount *record = [CCCoreData getActiveAccount];
  2090. if([record.account isEqualToString:metadataNet.account] == NO)
  2091. return;
  2092. [CCCoreData updateShare:items sharesLink:app.sharesLink sharesUserAndGroup:app.sharesUserAndGroup activeAccount:app.activeAccount activeUrl:app.activeUrl];
  2093. if (openWindow) {
  2094. if (_shareOC) {
  2095. [_shareOC reloadData];
  2096. } else {
  2097. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadataNet.fileID, app.activeAccount] context:nil];
  2098. // Apriamo la view
  2099. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  2100. _shareOC.delegate = self;
  2101. _shareOC.metadata = metadata;
  2102. _shareOC.serverUrl = metadataNet.serverUrl;
  2103. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  2104. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  2105. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  2106. [self presentViewController:_shareOC animated:YES completion:nil];
  2107. }
  2108. }
  2109. [self tableViewReload];
  2110. }
  2111. - (void)requestSharedByServer
  2112. {
  2113. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2114. metadataNet.action = actionReadShareServer;
  2115. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2116. }
  2117. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2118. {
  2119. [_hud hideHud];
  2120. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  2121. if (_shareOC)
  2122. [_shareOC reloadData];
  2123. [self tableViewReload];
  2124. if (errorCode == 401)
  2125. [self changePasswordAccount];
  2126. }
  2127. - (void)share:(CCMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  2128. {
  2129. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2130. metadataNet.action = actionShare;
  2131. metadataNet.fileID = metadata.fileID;
  2132. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2133. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2134. metadataNet.password = password;
  2135. metadataNet.selector = selectorShare;
  2136. metadataNet.serverUrl = serverUrl;
  2137. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2138. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2139. }
  2140. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  2141. {
  2142. [_hud hideHud];
  2143. // rimuoviamo la condivisione da db
  2144. [CCCoreData unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:app.sharesLink sharesUserAndGroup:app.sharesUserAndGroup activeAccount:app.activeAccount];
  2145. if (_shareOC)
  2146. [_shareOC reloadData];
  2147. [self tableViewReload];
  2148. }
  2149. - (void)unShare:(NSString *)share metadata:(CCMetadata *)metadata serverUrl:(NSString *)serverUrl
  2150. {
  2151. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2152. metadataNet.action = actionUnShare;
  2153. metadataNet.fileID = metadata.fileID;
  2154. metadataNet.fileName = metadata.fileName;
  2155. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2156. metadataNet.selector = selectorUnshare;
  2157. metadataNet.serverUrl = serverUrl;
  2158. metadataNet.share = share;
  2159. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2160. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2161. }
  2162. - (void)updateShare:(NSString *)share metadata:(CCMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  2163. {
  2164. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2165. metadataNet.action = actionUpdateShare;
  2166. metadataNet.fileID = metadata.fileID;
  2167. metadataNet.expirationTime = expirationTime;
  2168. metadataNet.password = password;
  2169. metadataNet.selector = selectorUpdateShare;
  2170. metadataNet.serverUrl = serverUrl;
  2171. metadataNet.share = share;
  2172. metadataNet.sharePermission = permission;
  2173. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2174. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2175. }
  2176. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  2177. {
  2178. [_hud hideHud];
  2179. if (_shareOC)
  2180. [_shareOC reloadUserAndGroup:items];
  2181. }
  2182. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2183. {
  2184. [_hud hideHud];
  2185. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  2186. }
  2187. - (void)getUserAndGroup:(NSString *)find
  2188. {
  2189. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2190. metadataNet.action = actionGetUserAndGroup;
  2191. metadataNet.options = find;
  2192. metadataNet.selector = selectorGetUserAndGroup;
  2193. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2194. [_hud visibleIndeterminateHud];
  2195. }
  2196. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(CCMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2197. {
  2198. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2199. metadataNet.action = actionShareWith;
  2200. metadataNet.fileID = metadata.fileID;
  2201. metadataNet.directoryID = directoryID;
  2202. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2203. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2204. metadataNet.serverUrl = serverUrl;
  2205. metadataNet.selector = selectorShare;
  2206. metadataNet.share = user;
  2207. metadataNet.shareeType = shareeType;
  2208. metadataNet.sharePermission = permission;
  2209. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2210. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2211. }
  2212. - (void)openWindowShare:(CCMetadata *)metadata
  2213. {
  2214. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2215. metadataNet.action = actionReadShareServer;
  2216. metadataNet.fileID = metadata.fileID;
  2217. metadataNet.fileName = metadata.fileName;
  2218. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2219. metadataNet.selector = selectorOpenWindowShare;
  2220. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2221. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2222. [_hud visibleIndeterminateHud];
  2223. }
  2224. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2225. {
  2226. CGPoint location = [tapGesture locationInView:self.tableView];
  2227. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2228. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2229. if (metadata)
  2230. [self openWindowShare:metadata];
  2231. }
  2232. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2233. {
  2234. CGPoint location = [tapGesture locationInView:self.tableView];
  2235. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2236. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2237. if (metadata) {
  2238. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2239. vc.metadata = metadata;
  2240. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2241. [self presentViewController:vc animated:YES completion:nil];
  2242. }
  2243. }
  2244. #pragma --------------------------------------------------------------------------------------------
  2245. #pragma mark ===== Favorite =====
  2246. #pragma --------------------------------------------------------------------------------------------
  2247. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2248. {
  2249. [CCCoreData setMetadataFavoriteFileID:metadataNet.fileID favorite:[metadataNet.options boolValue] activeAccount:app.activeAccount context:nil];
  2250. _dateReadDataSource = nil;
  2251. if (_isSearchMode)
  2252. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  2253. else
  2254. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  2255. CCMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadataNet.fileID, app.activeAccount] context:nil];
  2256. if (metadata.directory && metadata.favorite) {
  2257. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileNameData];
  2258. [[CCSynchronize sharedSynchronize] addFavoriteFolder:dir];
  2259. }
  2260. }
  2261. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2262. {
  2263. }
  2264. - (void)addFavorite:(CCMetadata *)metadata
  2265. {
  2266. if (metadata.directory) {
  2267. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2268. } else {
  2269. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2270. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2271. }
  2272. }
  2273. - (void)removeFavorite:(CCMetadata *)metadata
  2274. {
  2275. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2276. }
  2277. #pragma --------------------------------------------------------------------------------------------
  2278. #pragma mark ===== Offline =====
  2279. #pragma --------------------------------------------------------------------------------------------
  2280. - (void)addOffline:(CCMetadata *)metadata
  2281. {
  2282. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2283. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddOffline selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2284. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2285. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2286. }
  2287. - (void)removeOffline:(CCMetadata *)metadata
  2288. {
  2289. [CCCoreData setOfflineLocalFileID:metadata.fileID offline:NO activeAccount:app.activeAccount];
  2290. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2291. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2292. }
  2293. #pragma --------------------------------------------------------------------------------------------
  2294. #pragma mark ===== Local =====
  2295. #pragma --------------------------------------------------------------------------------------------
  2296. - (void)addLocal:(CCMetadata *)metadata
  2297. {
  2298. if (metadata.errorPasscode || !metadata.uuid) return;
  2299. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2300. if ([metadata.type isEqualToString: k_metadataType_file])
  2301. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddLocal selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2302. if ([metadata.type isEqualToString: k_metadataType_template]) {
  2303. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileName]];
  2304. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess];
  2305. }
  2306. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2307. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2308. }
  2309. #pragma --------------------------------------------------------------------------------------------
  2310. #pragma mark ===== Open in... =====
  2311. #pragma --------------------------------------------------------------------------------------------
  2312. - (void)openIn:(CCMetadata *)metadata
  2313. {
  2314. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2315. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2316. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2317. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2318. }
  2319. #pragma --------------------------------------------------------------------------------------------
  2320. #pragma mark ===== Remove Local File =====
  2321. #pragma --------------------------------------------------------------------------------------------
  2322. - (void)removeLocalFile:(CCMetadata *)metadata
  2323. {
  2324. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2325. [CCCoreData deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (fileID == %@)", app.activeAccount, metadata.fileID]];
  2326. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  2327. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:nil];
  2328. }
  2329. #pragma --------------------------------------------------------------------------------------------
  2330. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2331. #pragma --------------------------------------------------------------------------------------------
  2332. - (void)orderTable:(NSString *)order
  2333. {
  2334. [CCUtility setOrderSettings:order];
  2335. // Clear data-read of DataSource
  2336. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2337. // new menu
  2338. [self createReMainMenu];
  2339. }
  2340. - (void)ascendingTable:(BOOL)ascending
  2341. {
  2342. [CCUtility setAscendingSettings:ascending];
  2343. // Clear data-read of DataSource
  2344. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2345. // new menu
  2346. [self createReMainMenu];
  2347. }
  2348. - (void)directoryOnTop:(BOOL)directoryOnTop
  2349. {
  2350. [CCUtility setDirectoryOnTop:directoryOnTop];
  2351. // Clear data-read of DataSource
  2352. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2353. // new menu
  2354. [self createReMainMenu];
  2355. }
  2356. - (void)tableGroupBy:(NSString *)groupBy
  2357. {
  2358. [CCUtility setGroupBySettings:groupBy];
  2359. // Clear data-read of DataSource
  2360. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2361. // new menu
  2362. [self createReMainMenu];
  2363. }
  2364. #pragma --------------------------------------------------------------------------------------------
  2365. #pragma mark ==== Menu LOGO ====
  2366. #pragma --------------------------------------------------------------------------------------------
  2367. - (void)menuLogo
  2368. {
  2369. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2370. return;
  2371. // Brand
  2372. if (k_option_disable_multiaccount)
  2373. return;
  2374. if ([app.netQueue operationCount] > 0 || [app.netQueueDownload operationCount] > 0 || [app.netQueueDownloadWWan operationCount] > 0 || [app.netQueueUpload operationCount] > 0 || [app.netQueueUploadWWan operationCount] > 0 || [CCCoreData countTableAutomaticUploadForAccount:app.activeAccount selector:nil] > 0) {
  2375. [app messageNotification:@"_transfers_in_queue_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo];
  2376. return;
  2377. }
  2378. NSArray *listTableAccount = [CCCoreData getAllTableAccount];
  2379. NSMutableArray *menuArray = [NSMutableArray new];
  2380. for (TableAccount *record in listTableAccount) {
  2381. if ([record.account isEqualToString:app.activeAccount]) continue;
  2382. CCMenuItem *item = [[CCMenuItem alloc] init];
  2383. item.title = [record.account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2384. item.argument = record.account;
  2385. item.image = [UIImage imageNamed:image_MenuLogoUser];
  2386. item.target = self;
  2387. item.action = @selector(changeDefaultAccount:);
  2388. [menuArray addObject:item];
  2389. }
  2390. if ([menuArray count] == 0)
  2391. return;
  2392. OptionalConfiguration options;
  2393. Color textColor, backgroundColor;
  2394. textColor.R = 0;
  2395. textColor.G = 0;
  2396. textColor.B = 0;
  2397. backgroundColor.R = 1;
  2398. backgroundColor.G = 1;
  2399. backgroundColor.B = 1;
  2400. NSInteger originY = 60;
  2401. options.arrowSize = 9;
  2402. options.marginXSpacing = 7;
  2403. options.marginYSpacing = 10;
  2404. options.intervalSpacing = 20;
  2405. options.menuCornerRadius = 6.5;
  2406. options.maskToBackground = NO;
  2407. options.shadowOfMenu = YES;
  2408. options.hasSeperatorLine = YES;
  2409. options.seperatorLineHasInsets = YES;
  2410. options.textColor = textColor;
  2411. options.menuBackgroundColor = backgroundColor;
  2412. CGRect rect = self.view.frame;
  2413. rect.origin.y = rect.origin.y + originY;
  2414. rect.size.height = rect.size.height - originY;
  2415. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2416. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2417. }
  2418. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2419. {
  2420. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2421. // STOP, erase all in queue networking
  2422. [app cancelAllOperations];
  2423. [[CCNetworking sharedNetworking] settingSessionsDownload:YES upload:YES taskStatus:k_taskStatusCancel activeAccount:app.activeAccount activeUser:app.activeUser activeUrl:app.activeUrl];
  2424. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2425. TableAccount *tableAccount = [CCCoreData setActiveAccount:[sender argument]];
  2426. if (tableAccount)
  2427. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activePassword:tableAccount.password];
  2428. // go to home sweet home
  2429. [[NSNotificationCenter defaultCenter] postNotificationName:@"initializeMain" object:nil];
  2430. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2431. });
  2432. }
  2433. #pragma --------------------------------------------------------------------------------------------
  2434. #pragma mark ==== ReMenu ====
  2435. #pragma --------------------------------------------------------------------------------------------
  2436. - (void)createReMenuBackgroundView:(REMenu *)menu
  2437. {
  2438. __block CGFloat navigationBarH = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;
  2439. _reMenuBackgroundView.frame = CGRectMake(0, navigationBarH, self.view.frame.size.width, self.view.frame.size.height);
  2440. [UIView animateWithDuration:0.2 animations:^{
  2441. float height = (self.view.frame.size.height + navigationBarH) - (menu.menuView.frame.size.height - self.navigationController.navigationBar.frame.size.height + 3);
  2442. if (height < self.tabBarController.tabBar.frame.size.height)
  2443. height = self.tabBarController.tabBar.frame.size.height;
  2444. _reMenuBackgroundView.frame = CGRectMake(0, self.view.frame.size.height + navigationBarH, self.view.frame.size.width, - height);
  2445. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2446. }];
  2447. }
  2448. - (void)createReMainMenu
  2449. {
  2450. NSString *ordinamento;
  2451. NSString *groupBy = _directoryGroupBy;
  2452. __block NSString *nuovoOrdinamento;
  2453. NSString *titoloNuovo, *titoloAttuale;
  2454. BOOL ascendente;
  2455. __block BOOL nuovoAscendente;
  2456. UIImage *image;
  2457. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2458. if (app.selezionaItem == nil) app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_seleziona] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2459. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2460. [self tableViewSelect:YES];
  2461. }
  2462. }];
  2463. else app.selezionaItem = [app.selezionaItem initWithTitle:NSLocalizedString(@"_select_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_seleziona] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2464. if ([_sectionDataSource.allRecordsDataSource count] > 0)
  2465. [self tableViewSelect:YES];
  2466. }];
  2467. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2468. ordinamento = _directoryOrder;
  2469. if ([ordinamento isEqualToString:@"fileName"]) {
  2470. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuOrdeyByDate] color:[NCBrandColor sharedInstance].brand];
  2471. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2472. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2473. nuovoOrdinamento = @"fileDate";
  2474. }
  2475. if ([ordinamento isEqualToString:@"fileDate"]) {
  2476. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuOrderByFileName] color:[NCBrandColor sharedInstance].brand];
  2477. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2478. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2479. nuovoOrdinamento = @"fileName";
  2480. }
  2481. if (app.ordinaItem == nil) app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2482. [self orderTable:nuovoOrdinamento];
  2483. }];
  2484. else app.ordinaItem = [app.ordinaItem initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2485. [self orderTable:nuovoOrdinamento];
  2486. }];
  2487. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2488. ascendente = [CCUtility getAscendingSettings];
  2489. if (ascendente) {
  2490. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuOrdinamentoDiscendente] color:[NCBrandColor sharedInstance].brand];
  2491. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2492. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2493. nuovoAscendente = false;
  2494. }
  2495. if (!ascendente) {
  2496. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuOrdinamentoAscendente] color:[NCBrandColor sharedInstance].brand];
  2497. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2498. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2499. nuovoAscendente = true;
  2500. }
  2501. if (app.ascendenteItem == nil) app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2502. [self ascendingTable:nuovoAscendente];
  2503. }];
  2504. else app.ascendenteItem = [app.ascendenteItem initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2505. [self ascendingTable:nuovoAscendente];
  2506. }];
  2507. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2508. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2509. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2510. if (app.alphabeticItem == nil) app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuGroupByAlphabetic] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2511. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2512. else [self tableGroupBy:@"alphabetic"];
  2513. }];
  2514. else app.alphabeticItem = [app.alphabeticItem initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuGroupByAlphabetic] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2515. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2516. else [self tableGroupBy:@"alphabetic"];
  2517. }];
  2518. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2519. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2520. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2521. if (app.typefileItem == nil) app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuGroupByTypeFile] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2522. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2523. else [self tableGroupBy:@"typefile"];
  2524. }];
  2525. else app.typefileItem = [app.typefileItem initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuGroupByTypeFile] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2526. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2527. else [self tableGroupBy:@"typefile"];
  2528. }];
  2529. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2530. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2531. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2532. if (app.dateItem == nil) app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuGroupByDate] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2533. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2534. else [self tableGroupBy:@"date"];
  2535. }];
  2536. else app.dateItem = [app.dateItem initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuGroupByDate] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2537. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2538. else [self tableGroupBy:@"date"];
  2539. }];
  2540. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2541. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2542. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2543. if (app.directoryOnTopItem == nil) app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuDirectoryOnTop] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2544. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2545. else [self directoryOnTop:YES];
  2546. }];
  2547. else app.directoryOnTopItem = [app.directoryOnTopItem initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_MenuDirectoryOnTop] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2548. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2549. else [self directoryOnTop:YES];
  2550. }];
  2551. // REMENU --------------------------------------------------------------------------------------------------------------
  2552. if (app.reMainMenu == nil) app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2553. else app.reMainMenu = [app.reMainMenu initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2554. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2555. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2556. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2557. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2558. app.reMainMenu.separatorHeight = 0.5;
  2559. app.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2560. app.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2561. app.reMainMenu.textColor = [UIColor blackColor];
  2562. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2563. app.reMainMenu.textShadowColor = nil;
  2564. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2565. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2566. app.reMainMenu.highlightedBackgroundColor = [NCBrandColor sharedInstance].selectBackgrond;
  2567. app.reMainMenu.highlightedSeparatorColor = nil;
  2568. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2569. app.reMainMenu.highlightedTextShadowColor = nil;
  2570. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2571. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2572. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2573. app.reMainMenu.subtitleTextShadowColor = nil;
  2574. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2575. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2576. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2577. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2578. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2579. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2580. app.reMainMenu.borderWidth = 0.3;
  2581. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2582. app.reMainMenu.animationDuration = 0.2;
  2583. app.reMainMenu.closeAnimationDuration = 0.2;
  2584. app.reMainMenu.bounce = NO;
  2585. [app.reMainMenu setClosePreparationBlock:^{
  2586. // Backgroun reMenu (Gesture)
  2587. [_reMenuBackgroundView removeFromSuperview];
  2588. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2589. }];
  2590. }
  2591. - (void)toggleReMainMenu
  2592. {
  2593. if (app.reMainMenu.isOpen) {
  2594. [app.reMainMenu close];
  2595. } else {
  2596. [app.reMainMenu showFromNavigationController:self.navigationController];
  2597. // Backgroun reMenu & (Gesture)
  2598. [self createReMenuBackgroundView:app.reMainMenu];
  2599. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2600. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2601. }
  2602. }
  2603. - (void)createReSelectMenu
  2604. {
  2605. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2606. if (app.deleteItem == nil) app.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_deleteSelectedFiles] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2607. [self deleteSelectionFile];
  2608. }];
  2609. else app.deleteItem = [app.deleteItem initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_deleteSelectedFiles] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2610. [self deleteSelectionFile];
  2611. }];
  2612. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2613. if (app.moveItem == nil) app.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_moveSelectedFiles] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2614. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2615. }];
  2616. else app.moveItem = [app.moveItem initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_moveSelectedFiles] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2617. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2618. }];
  2619. if (app.isCryptoCloudMode) {
  2620. // ITEM ENCRYPTED ------------------------------------------------------------------------------------------------------
  2621. if (app.encryptItem == nil) app.encryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_encryptedSelectedFiles] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2622. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2623. }];
  2624. else app.encryptItem = [app.encryptItem initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_encryptedSelectedFiles] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2625. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2626. }];
  2627. // ITEM DECRYPTED ----------------------------------------------------------------------------------------------------
  2628. if (app.decryptItem == nil) app.decryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_decryptedSelectedFiles] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2629. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2630. }];
  2631. else app.decryptItem = [app.decryptItem initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_decryptedSelectedFiles] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2632. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2633. }];
  2634. }
  2635. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2636. if (app.downloadItem == nil) app.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_downloadSelectedFiles] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2637. [self downloadSelectedFiles];
  2638. }];
  2639. else app.downloadItem = [app.downloadItem initWithTitle:NSLocalizedString(@"_download_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_downloadSelectedFiles] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2640. [self downloadSelectedFiles];
  2641. }];
  2642. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2643. if (app.saveItem == nil) app.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_saveSelectedFiles] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2644. [self saveSelectedFiles];
  2645. }];
  2646. else app.saveItem = [app.saveItem initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_saveSelectedFiles] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2647. [self saveSelectedFiles];
  2648. }];
  2649. // REMENU --------------------------------------------------------------------------------------------------------------
  2650. if (app.isCryptoCloudMode) {
  2651. if (app.reSelectMenu == nil)
  2652. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2653. else
  2654. app.reSelectMenu = [app.reSelectMenu initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2655. } else {
  2656. if (app.reSelectMenu == nil)
  2657. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2658. else
  2659. app.reSelectMenu = [app.reSelectMenu initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2660. }
  2661. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2662. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2663. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2664. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2665. app.reSelectMenu.separatorHeight = 0.5;
  2666. app.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2667. app.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2668. app.reSelectMenu.textColor = [UIColor blackColor];
  2669. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2670. app.reSelectMenu.textShadowColor = nil;
  2671. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2672. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2673. app.reSelectMenu.highlightedBackgroundColor = [NCBrandColor sharedInstance].selectBackgrond;
  2674. app.reSelectMenu.highlightedSeparatorColor = nil;
  2675. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2676. app.reSelectMenu.highlightedTextShadowColor = nil;
  2677. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2678. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2679. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2680. app.reSelectMenu.subtitleTextShadowColor = nil;
  2681. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2682. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2683. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2684. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2685. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2686. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2687. app.reSelectMenu.borderWidth = 0.3;
  2688. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2689. app.reSelectMenu.closeAnimationDuration = 0.2;
  2690. app.reSelectMenu.animationDuration = 0.2;
  2691. app.reSelectMenu.bounce = NO;
  2692. [app.reSelectMenu setClosePreparationBlock:^{
  2693. // Backgroun reMenu (Gesture)
  2694. [_reMenuBackgroundView removeFromSuperview];
  2695. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2696. }];
  2697. }
  2698. - (void)toggleReSelectMenu
  2699. {
  2700. if (app.reSelectMenu.isOpen) {
  2701. [app.reSelectMenu close];
  2702. } else {
  2703. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2704. // Backgroun reMenu & (Gesture)
  2705. [self createReMenuBackgroundView:app.reSelectMenu];
  2706. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2707. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2708. }
  2709. }
  2710. #pragma --------------------------------------------------------------------------------------------
  2711. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2712. #pragma --------------------------------------------------------------------------------------------
  2713. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2714. {
  2715. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2716. UITableView *tableView = (UITableView*)self.view;
  2717. CGPoint touchPoint = [recognizer locationInView:self.view];
  2718. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2719. if (indexPath)
  2720. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2721. else
  2722. _metadata = nil;
  2723. [self becomeFirstResponder];
  2724. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2725. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2726. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2727. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2728. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2729. UIMenuItem *pasteFileEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_encrypted_", nil) action:@selector(pasteFileEncrypted:)];
  2730. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2731. UIMenuItem *pasteFilesEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_encrypted_", nil) action:@selector(pasteFilesEncrypted:)];
  2732. if (app.isCryptoCloudMode)
  2733. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, pasteFileEncryptedItem, pasteFilesEncryptedItem, nil]];
  2734. else
  2735. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2736. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2737. [menuController setMenuVisible:YES animated:YES];
  2738. }
  2739. }
  2740. - (BOOL)canBecomeFirstResponder
  2741. {
  2742. return YES;
  2743. }
  2744. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2745. {
  2746. // For copy file, copy files, Open in ... :
  2747. //
  2748. // NO Directory
  2749. // NO Error Passcode
  2750. // NO In Session mode (download/upload)
  2751. // NO Template
  2752. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2753. if (_isSelectedMode == NO && _metadata && !_metadata.directory && !_metadata.errorPasscode && [_metadata.session length] == 0 && ![_metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2754. // NO Cryptated with Title lenght = 0
  2755. if (!_metadata.cryptated || (_metadata.cryptated && _metadata.title.length > 0))
  2756. return YES;
  2757. }
  2758. return NO;
  2759. }
  2760. if (@selector(copyFiles:) == action) {
  2761. if (_isSelectedMode) {
  2762. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2763. for (CCMetadata *metadata in selectedMetadatas) {
  2764. if (!metadata.directory && !metadata.errorPasscode && metadata.session.length == 0 && ![metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2765. // NO Cryptated with Title lenght = 0
  2766. if (!metadata.cryptated || (metadata.cryptated && metadata.title.length > 0))
  2767. return YES;
  2768. }
  2769. }
  2770. }
  2771. return NO;
  2772. }
  2773. if (@selector(pasteFile:) == action || @selector(pasteFileEncrypted:) == action) {
  2774. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2775. NSArray *items = [pasteboard items];
  2776. if ([items count] == 1) {
  2777. // Value : (NSData) metadata
  2778. NSDictionary *dic = [items objectAtIndex:0];
  2779. NSData *dataMetadata = [dic objectForKey: k_metadataKeyedUnarchiver];
  2780. CCMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2781. TableAccount *account = [CCCoreData getTableAccountFromAccount:metadata.account];
  2782. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2783. if (directoryUser) {
  2784. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]])
  2785. return YES;
  2786. }
  2787. return NO;
  2788. } else return NO;
  2789. }
  2790. if (@selector(pasteFiles:) == action || @selector(pasteFilesEncrypted:) == action) {
  2791. BOOL isValid = NO;
  2792. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2793. NSArray *items = [pasteboard items];
  2794. if ([items count] <= 1) return NO;
  2795. for (NSDictionary *dic in items) {
  2796. // Value : (NSData) metadata
  2797. NSData *dataMetadata = [dic objectForKey: k_metadataKeyedUnarchiver];
  2798. CCMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2799. TableAccount *account = [CCCoreData getTableAccountFromAccount:metadata.account];
  2800. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2801. if (directoryUser) {
  2802. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]])
  2803. isValid = YES;
  2804. }
  2805. }
  2806. return isValid;
  2807. }
  2808. return NO;
  2809. }
  2810. /************************************ COPY ************************************/
  2811. - (void)copyFile:(id)sender
  2812. {
  2813. // Remove all item
  2814. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2815. pasteboard.items = [[NSArray alloc] init];
  2816. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2817. [self copyFileToPasteboard:_metadata];
  2818. } else {
  2819. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2820. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2821. }
  2822. }
  2823. - (void)copyFiles:(id)sender
  2824. {
  2825. // Remove all item
  2826. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2827. pasteboard.items = [[NSArray alloc] init];
  2828. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2829. for (CCMetadata *metadata in selectedMetadatas) {
  2830. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2831. [self copyFileToPasteboard:metadata];
  2832. } else {
  2833. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2834. [[CCNetworking sharedNetworking] downloadFile:metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2835. }
  2836. }
  2837. [self tableViewSelect:NO];
  2838. }
  2839. - (void)copyFileToPasteboard:(CCMetadata *)metadata
  2840. {
  2841. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2842. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2843. // Value : (NSData) metadata
  2844. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata], k_metadataKeyedUnarchiver,nil];
  2845. [items addObject:item];
  2846. [pasteboard setItems:items];
  2847. }
  2848. /************************************ OPEN IN ... ************************************/
  2849. - (void)openinFile:(id)sender
  2850. {
  2851. [self openIn:_metadata];
  2852. }
  2853. /************************************ PASTE ************************************/
  2854. - (void)pasteFile:(id)sender
  2855. {
  2856. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2857. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2858. }
  2859. - (void)pasteFileEncrypted:(id)sender
  2860. {
  2861. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2862. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2863. }
  2864. - (void)pasteFiles:(id)sender
  2865. {
  2866. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2867. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2868. }
  2869. - (void)pasteFilesEncrypted:(id)sender
  2870. {
  2871. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2872. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2873. }
  2874. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2875. {
  2876. for (NSDictionary *dic in items) {
  2877. // Value : (NSData) metadata
  2878. NSData *dataMetadata = [dic objectForKey: k_metadataKeyedUnarchiver];
  2879. CCMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2880. TableAccount *account = [CCCoreData getTableAccountFromAccount:metadata.account];
  2881. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2882. if (directoryUser) {
  2883. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]]) {
  2884. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint]];
  2885. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:_serverUrl cryptated:cryptated onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  2886. }
  2887. }
  2888. }
  2889. }
  2890. #pragma --------------------------------------------------------------------------------------------
  2891. #pragma mark ===== Lock Passcode =====
  2892. #pragma --------------------------------------------------------------------------------------------
  2893. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2894. {
  2895. return _failedAttempts;
  2896. }
  2897. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2898. {
  2899. return _lockUntilDate;
  2900. }
  2901. - (void)passcodeViewCloseButtonPressed:(id)sender
  2902. {
  2903. [self dismissViewControllerAnimated:YES completion:nil];
  2904. }
  2905. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2906. {
  2907. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2908. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2909. _lockUntilDate = nil;
  2910. _failedAttempts = 0;
  2911. aResultHandler(YES);
  2912. } else aResultHandler(NO);
  2913. } else aResultHandler(YES);
  2914. }
  2915. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2916. {
  2917. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2918. switch (aViewController.type) {
  2919. case BKPasscodeViewControllerCheckPasscodeType: {
  2920. if (aViewController.fromType == CCBKPasscodeFromPasscode) {
  2921. // verifichiamo se il passcode è corretto per il seguente file -> UUID
  2922. if ([[CCCrypto sharedManager] verifyPasscode:aPasscode uuid:_metadata.uuid text:_metadata.title]) {
  2923. // scriviamo il passcode
  2924. [CCUtility setKeyChainPasscodeForUUID:_metadata.uuid conPasscode:aPasscode];
  2925. [self readFolderWithForced:YES serverUrl:_serverUrl];
  2926. } else {
  2927. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2928. [alertView show];
  2929. }
  2930. }
  2931. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2932. // possiamo procedere alla prossima directory
  2933. [self performSegueDirectoryWithControlPasscode:false];
  2934. // avviamo la sessione Passcode Lock con now
  2935. app.sessionePasscodeLock = [NSDate date];
  2936. }
  2937. // disattivazione lock cartella
  2938. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2939. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2940. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2941. if ([CCCoreData setDirectoryUnLock:lockServerUrl activeAccount:app.activeAccount] == NO) {
  2942. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  2943. }
  2944. [self.tableView reloadData];
  2945. }
  2946. }
  2947. break;
  2948. default:
  2949. break;
  2950. }
  2951. }
  2952. - (void)comandoLockPassword
  2953. {
  2954. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2955. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2956. // se non è abilitato il Lock Passcode esci
  2957. if ([[CCUtility getBlockCode] length] == 0) {
  2958. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2959. [alertView show];
  2960. return;
  2961. }
  2962. // se è richiesta la disattivazione si chiede la password
  2963. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) {
  2964. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2965. viewController.delegate = self;
  2966. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2967. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2968. viewController.inputViewTitlePassword = YES;
  2969. if ([CCUtility getSimplyBlockCode]) {
  2970. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2971. viewController.passcodeInputView.maximumLength = 6;
  2972. } else {
  2973. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2974. viewController.passcodeInputView.maximumLength = 64;
  2975. }
  2976. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2977. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2978. viewController.touchIDManager = touchIDManager;
  2979. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2980. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2981. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  2982. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2983. [self presentViewController:navigationController animated:YES completion:nil];
  2984. return;
  2985. }
  2986. // ---------------- ACTIVATE PASSWORD
  2987. if([CCCoreData setDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) {
  2988. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2989. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2990. } else {
  2991. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  2992. }
  2993. }
  2994. #pragma mark -
  2995. #pragma --------------------------------------------------------------------------------------------
  2996. #pragma mark ===== Swipe Tablet -> menu =====
  2997. #pragma --------------------------------------------------------------------------------------------
  2998. // more
  2999. - (NSString *)tableView:(UITableView *)tableView titleForSwipeAccessoryButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
  3000. return NSLocalizedString(@"_more_", nil);
  3001. }
  3002. - (void)tableView:(UITableView *)tableView swipeAccessoryButtonPushedForRowAtIndexPath:(NSIndexPath *)indexPath
  3003. {
  3004. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3005. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  3006. NSString *titoloCriptaDecripta, *titoloOffline, *titoloLock, *titleOfflineFolder, *titleFavorite;
  3007. BOOL offlineFolder = NO;
  3008. if (_metadata.cryptated) titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_decrypt_", nil)];
  3009. else titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_", nil)];
  3010. if ([CCCoreData isOfflineLocalFileID:_metadata.fileID activeAccount:app.activeAccount]) titoloOffline = [NSString stringWithFormat:NSLocalizedString(@"_remove_offline_", nil)];
  3011. else titoloOffline = [NSString stringWithFormat:NSLocalizedString(@"_add_offline_", nil)];
  3012. NSString *offlineServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3013. if (_metadata.directory && [CCCoreData isOfflineDirectoryServerUrl:offlineServerUrl activeAccount:app.activeAccount]) {
  3014. titleOfflineFolder = [NSString stringWithFormat:NSLocalizedString(@"_remove_offline_", nil)];
  3015. offlineFolder = YES;
  3016. } else titleOfflineFolder = [NSString stringWithFormat:NSLocalizedString(@"_add_offline_", nil)];
  3017. if (_metadata.favorite) {
  3018. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  3019. } else {
  3020. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  3021. }
  3022. if (_metadata.directory) {
  3023. // calcolo lockServerUrl
  3024. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3025. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  3026. else titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  3027. }
  3028. TableLocalFile *recordLocalFile = [CCCoreData getLocalFileWithFileID:_metadata.fileID activeAccount:app.activeAccount];
  3029. /******************************************* AHKActionSheet *******************************************/
  3030. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.view title:nil];
  3031. actionSheet.animationDuration = 0.2;
  3032. actionSheet.blurRadius = 0.0f;
  3033. actionSheet.blurTintColor = [UIColor colorWithWhite:0.0f alpha:0.50f];
  3034. actionSheet.buttonHeight = 50.0;
  3035. actionSheet.cancelButtonHeight = 50.0f;
  3036. actionSheet.separatorHeight = 5.0f;
  3037. actionSheet.automaticallyTintButtonImages = @(NO);
  3038. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].cryptocloud };
  3039. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  3040. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].brand };
  3041. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  3042. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  3043. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  3044. /******************************************* DIRECTORY *******************************************/
  3045. if (_metadata.directory) {
  3046. BOOL lockDirectory = NO;
  3047. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3048. // Directory bloccata ?
  3049. if ([CCCoreData isDirectoryLock:dirServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3050. NSString *cameraUploadFolderName = [CCCoreData getCameraUploadFolderNameActiveAccount:app.activeAccount];
  3051. NSString *cameraUploadFolderPath = [CCCoreData getCameraUploadFolderPathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  3052. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3053. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:_metadata.iconName] color:[NCBrandColor sharedInstance].brand]
  3054. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3055. height: 50.0
  3056. type: AHKActionSheetButtonTypeDisabled
  3057. handler: nil
  3058. ];
  3059. if (!lockDirectory && !_metadata.cryptated) {
  3060. [actionSheet addButtonWithTitle:titleFavorite
  3061. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetFavorite] color:[NCBrandColor sharedInstance].brand]
  3062. backgroundColor:[UIColor whiteColor]
  3063. height: 50.0
  3064. type:AHKActionSheetButtonTypeDefault
  3065. handler:^(AHKActionSheet *as) {
  3066. // close swipe
  3067. [self setEditing:NO animated:YES];
  3068. if (_metadata.favorite)
  3069. [self removeFavorite:_metadata];
  3070. else
  3071. [self addFavorite:_metadata];
  3072. }];
  3073. }
  3074. if (_metadata.cryptated == NO && app.hasServerShareSupport && !lockDirectory) {
  3075. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3076. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetShare] color:[NCBrandColor sharedInstance].brand]
  3077. backgroundColor:[UIColor whiteColor]
  3078. height: 50.0
  3079. type:AHKActionSheetButtonTypeDefault
  3080. handler:^(AHKActionSheet *as) {
  3081. // close swipe
  3082. [self setEditing:NO animated:YES];
  3083. [self openWindowShare:_metadata];
  3084. }];
  3085. }
  3086. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory) {
  3087. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3088. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetRename] color:[NCBrandColor sharedInstance].brand]
  3089. backgroundColor:[UIColor whiteColor]
  3090. height: 50.0
  3091. type:AHKActionSheetButtonTypeDefault
  3092. handler:^(AHKActionSheet *as) {
  3093. // close swipe
  3094. [self setEditing:NO animated:YES];
  3095. //chiediamo il nome del file
  3096. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3097. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3098. alertView.tag = alertRename;
  3099. UITextField *textField = [alertView textFieldAtIndex:0];
  3100. textField.text = _metadata.fileNamePrint;
  3101. [alertView show];
  3102. }];
  3103. }
  3104. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory) {
  3105. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3106. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetMove] color:[NCBrandColor sharedInstance].brand]
  3107. backgroundColor:[UIColor whiteColor]
  3108. height: 50.0
  3109. type:AHKActionSheetButtonTypeDefault
  3110. handler:^(AHKActionSheet *as) {
  3111. // close swipe
  3112. [self setEditing:NO animated:YES];
  3113. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3114. }];
  3115. }
  3116. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && _metadata.cryptated == NO) {
  3117. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  3118. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_folderphotocamera] color:[NCBrandColor sharedInstance].brand]
  3119. backgroundColor:[UIColor whiteColor]
  3120. height: 50.0
  3121. type:AHKActionSheetButtonTypeDefault
  3122. handler:^(AHKActionSheet *as) {
  3123. // close swipe
  3124. [self setEditing:NO animated:YES];
  3125. // Settings new folder Automatatic upload
  3126. NSString *oldPath = [CCCoreData getCameraUploadFolderPathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  3127. [CCCoreData setCameraUploadFolderName:_metadata.fileName activeAccount:app.activeAccount];
  3128. [CCCoreData setCameraUploadFolderPath:serverUrl activeUrl:app.activeUrl activeAccount:app.activeAccount];
  3129. [CCCoreData clearDateReadAccount:app.activeAccount serverUrl:oldPath directoryID:nil];
  3130. if (app.activeAccount.length > 0 && app.activePhotosCameraUpload)
  3131. [app.activePhotosCameraUpload reloadDatasourceForced];
  3132. [self readFolderWithForced:YES serverUrl:serverUrl];
  3133. NSLog(@"[LOG] Update Folder Photo");
  3134. NSString *folderCameraUpload = [CCCoreData getCameraUploadFolderNamePathActiveAccount:app.activeAccount activeUrl:app.activeUrl];
  3135. if ([folderCameraUpload length] > 0)
  3136. [[CCSynchronize sharedSynchronize] readFolderServerUrl:folderCameraUpload directoryID:[CCCoreData getDirectoryIDFromServerUrl:folderCameraUpload activeAccount:app.activeAccount] selector:selectorReadFolder];
  3137. }];
  3138. }
  3139. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES)) {
  3140. [actionSheet addButtonWithTitle:titoloLock
  3141. image:[UIImage imageNamed:image_actionSheetLock]
  3142. backgroundColor:[UIColor whiteColor]
  3143. height: 50.0
  3144. type:AHKActionSheetButtonTypeEncrypted
  3145. handler:^(AHKActionSheet *as) {
  3146. // close swipe
  3147. [self setEditing:NO animated:YES];
  3148. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  3149. }];
  3150. }
  3151. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory && app.isCryptoCloudMode) {
  3152. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3153. image:[UIImage imageNamed:image_actionSheetCrypto]
  3154. backgroundColor:[UIColor whiteColor]
  3155. height: 50.0
  3156. type:AHKActionSheetButtonTypeEncrypted
  3157. handler:^(AHKActionSheet *as) {
  3158. // close swipe
  3159. [self setEditing:NO animated:YES];
  3160. [self performSelector:@selector(encyptedDecryptedFolder) withObject:nil];
  3161. }];
  3162. }
  3163. [actionSheet show];
  3164. }
  3165. /******************************************* FILE *******************************************/
  3166. if ([_metadata.type isEqualToString: k_metadataType_file] && !_metadata.directory) {
  3167. UIImage *iconHeader;
  3168. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3169. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  3170. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  3171. else
  3172. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3173. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3174. image: iconHeader
  3175. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3176. height: 50.0
  3177. type: AHKActionSheetButtonTypeDisabled
  3178. handler: nil
  3179. ];
  3180. if (!_metadata.cryptated) {
  3181. [actionSheet addButtonWithTitle:titleFavorite
  3182. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetFavorite] color:[NCBrandColor sharedInstance].brand]
  3183. backgroundColor:[UIColor whiteColor]
  3184. height: 50.0
  3185. type:AHKActionSheetButtonTypeDefault
  3186. handler:^(AHKActionSheet *as) {
  3187. // close swipe
  3188. [self setEditing:NO animated:YES];
  3189. if (_metadata.favorite)
  3190. [self removeFavorite:_metadata];
  3191. else
  3192. [self addFavorite:_metadata];
  3193. }];
  3194. }
  3195. if (_metadata.cryptated == NO && app.hasServerShareSupport) {
  3196. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3197. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetShare] color:[NCBrandColor sharedInstance].brand]
  3198. backgroundColor:[UIColor whiteColor]
  3199. height: 50.0
  3200. type:AHKActionSheetButtonTypeDefault
  3201. handler:^(AHKActionSheet *as) {
  3202. // close swipe
  3203. [self setEditing:NO animated:YES];
  3204. [self openWindowShare:_metadata];
  3205. }];
  3206. }
  3207. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  3208. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetOpenIn] color:[NCBrandColor sharedInstance].brand]
  3209. backgroundColor:[UIColor whiteColor]
  3210. height: 50.0
  3211. type:AHKActionSheetButtonTypeDefault
  3212. handler:^(AHKActionSheet *as) {
  3213. // close swipe
  3214. [self setEditing:NO animated:YES];
  3215. [self performSelector:@selector(openIn:) withObject:_metadata];
  3216. }];
  3217. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3218. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetRename] color:[NCBrandColor sharedInstance].brand]
  3219. backgroundColor:[UIColor whiteColor]
  3220. height: 50.0
  3221. type:AHKActionSheetButtonTypeDefault
  3222. handler:^(AHKActionSheet *as) {
  3223. // close swipe
  3224. [self setEditing:NO animated:YES];
  3225. //chiediamo il nome del file
  3226. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3227. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3228. alertView.tag = alertRename;
  3229. UITextField *textField = [alertView textFieldAtIndex:0];
  3230. textField.text = _metadata.fileNamePrint;
  3231. [alertView show];
  3232. }];
  3233. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3234. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetMove] color:[NCBrandColor sharedInstance].brand]
  3235. backgroundColor:[UIColor whiteColor]
  3236. height: 50.0
  3237. type:AHKActionSheetButtonTypeDefault
  3238. handler:^(AHKActionSheet *as) {
  3239. // close swipe
  3240. [self setEditing:NO animated:YES];
  3241. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3242. }];
  3243. if (recordLocalFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3244. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3245. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetRemoveLocal] color:[NCBrandColor sharedInstance].brand]
  3246. backgroundColor:[UIColor whiteColor]
  3247. height: 50.0
  3248. type:AHKActionSheetButtonTypeDefault
  3249. handler:^(AHKActionSheet *as) {
  3250. // close swipe
  3251. [self setEditing:NO animated:YES];
  3252. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3253. }];
  3254. }
  3255. if (app.isCryptoCloudMode) {
  3256. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3257. image:[UIImage imageNamed:image_actionSheetCrypto]
  3258. backgroundColor:[UIColor whiteColor]
  3259. height: 50.0
  3260. type:AHKActionSheetButtonTypeEncrypted
  3261. handler:^(AHKActionSheet *as) {
  3262. // close swipe
  3263. [self setEditing:NO animated:YES];
  3264. [self performSelector:@selector(cmdEncryptedDecryptedFile) withObject:nil];
  3265. }];
  3266. }
  3267. [actionSheet show];
  3268. }
  3269. /******************************************* TEMPLATE *******************************************/
  3270. if ([_metadata.type isEqualToString: k_metadataType_template]) {
  3271. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3272. image: [UIImage imageNamed:_metadata.iconName]
  3273. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3274. height: 50.0
  3275. type: AHKActionSheetButtonTypeDisabled
  3276. handler: nil
  3277. ];
  3278. if ([_metadata.model isEqualToString:@"note"]) {
  3279. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3280. image:[UIImage imageNamed:image_actionSheetRename]
  3281. backgroundColor:[UIColor whiteColor]
  3282. height: 50.0
  3283. type:AHKActionSheetButtonTypeDefault
  3284. handler:^(AHKActionSheet *as) {
  3285. // close swipe
  3286. [self setEditing:NO animated:YES];
  3287. //chiediamo il nome del file
  3288. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3289. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3290. alertView.tag = alertRename;
  3291. UITextField *textField = [alertView textFieldAtIndex:0];
  3292. textField.text = _metadata.fileNamePrint;
  3293. [alertView show];
  3294. }];
  3295. }
  3296. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3297. image:[UIImage imageNamed:image_actionSheetMove]
  3298. backgroundColor:[UIColor whiteColor]
  3299. height: 50.0
  3300. type:AHKActionSheetButtonTypeDefault
  3301. handler:^(AHKActionSheet *as) {
  3302. // close swipe
  3303. [self setEditing:NO animated:YES];
  3304. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3305. }];
  3306. [actionSheet show];
  3307. }
  3308. }
  3309. - (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
  3310. {
  3311. return NSLocalizedString(@"_delete_", nil);
  3312. }
  3313. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3314. {
  3315. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3316. if (metadata == nil || metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0) return NO;
  3317. else return YES;
  3318. }
  3319. - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
  3320. {
  3321. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3322. if (metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0) return UITableViewCellEditingStyleNone;
  3323. else return UITableViewCellEditingStyleDelete;
  3324. }
  3325. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  3326. {
  3327. BOOL lockDirectory = NO;
  3328. // Directory locked ?
  3329. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account] addFileName:_metadata.fileNameData];
  3330. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3331. if (lockDirectory && editingStyle == UITableViewCellEditingStyleDelete) {
  3332. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError];
  3333. return;
  3334. }
  3335. if (editingStyle == UITableViewCellEditingStyleDelete) {
  3336. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3337. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  3338. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  3339. style:UIAlertActionStyleDestructive
  3340. handler:^(UIAlertAction *action) {
  3341. [self performSelector:@selector(deleteFile) withObject:nil];
  3342. }]];
  3343. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  3344. style:UIAlertActionStyleCancel
  3345. handler:^(UIAlertAction *action) {
  3346. [alertController dismissViewControllerAnimated:YES completion:nil];
  3347. }]];
  3348. alertController.popoverPresentationController.sourceView = self.view;
  3349. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  3350. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3351. [alertController.view layoutIfNeeded];
  3352. [self presentViewController:alertController animated:YES completion:nil];
  3353. }
  3354. }
  3355. #pragma --------------------------------------------------------------------------------------------
  3356. #pragma mark - ==== Datasource ====
  3357. #pragma --------------------------------------------------------------------------------------------
  3358. - (void)clearDateReadDataSource:(NSNotification *)notification
  3359. {
  3360. _dateReadDataSource = Nil;
  3361. [self reloadDatasource];
  3362. }
  3363. - (void)reloadDatasource
  3364. {
  3365. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  3366. }
  3367. - (void)reloadDatasource:(NSString *)serverUrl fileID:(NSString *)fileID selector:(NSString *)selector
  3368. {
  3369. // test
  3370. if (app.activeAccount.length == 0 || serverUrl.length == 0)
  3371. return;
  3372. // Search Mode
  3373. if(_isSearchMode) {
  3374. if ([selector length] == 0 || [selector isEqualToString:selectorSearch]) {
  3375. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3376. } else {
  3377. [self readFolderWithForced:NO serverUrl:serverUrl];
  3378. }
  3379. [self tableViewReload];
  3380. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3381. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3382. _noFilesSearchDescription = @"";
  3383. }
  3384. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3385. _noFilesSearchTitle = @"";
  3386. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3387. }
  3388. [self.tableView reloadEmptyDataSet];
  3389. return;
  3390. }
  3391. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3392. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3393. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  3394. [app.activeTransfers reloadDatasource];
  3395. } else {
  3396. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3397. if (main) {
  3398. [main reloadDatasource];
  3399. } else {
  3400. [self tableViewReload];
  3401. [app.activeTransfers reloadDatasource];
  3402. }
  3403. }
  3404. return;
  3405. }
  3406. // Offline folder ?
  3407. _isOfflineServerUrl = [CCCoreData isOfflineDirectoryServerUrl:_serverUrl activeAccount:app.activeAccount];
  3408. [app.activeTransfers reloadDatasource];
  3409. // Settaggio variabili per le ottimizzazioni
  3410. _directoryGroupBy = [CCUtility getGroupBySettings];
  3411. _directoryOrder = [CCUtility getOrderSettings];
  3412. // Controllo data lettura Data Source
  3413. NSDate *dateDateRecordDirectory = [CCCoreData getDateReadDirectoryID:[CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount] activeAccount:app.activeAccount];
  3414. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3415. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3416. _dateReadDataSource = [NSDate date];
  3417. // Data Source
  3418. NSArray *recordsTableMetadata = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@)", app.activeAccount, [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:app.activeAccount]] fieldOrder:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings]];
  3419. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3420. } else {
  3421. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3422. }
  3423. [self tableViewReload];
  3424. }
  3425. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3426. {
  3427. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3428. if (selectedRows.count > 0) {
  3429. for (NSIndexPath *selectionIndex in selectedRows) {
  3430. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3431. CCMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3432. [metadatas addObject:metadata];
  3433. }
  3434. }
  3435. return metadatas;
  3436. }
  3437. - (CCMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3438. {
  3439. NSInteger section = indexPath.section + 1;
  3440. NSInteger row = indexPath.row + 1;
  3441. NSInteger totSections =[_sectionDataSource.sections count] ;
  3442. if ((totSections < section) || (section > totSections)) {
  3443. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3444. return nil;
  3445. }
  3446. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3447. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3448. if (fileIDs) {
  3449. NSInteger totRows =[fileIDs count] ;
  3450. if ((totRows < row) || (row > totRows)) {
  3451. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3452. return nil;
  3453. }
  3454. } else {
  3455. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3456. return nil;
  3457. }
  3458. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3459. return [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3460. }
  3461. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3462. {
  3463. NSInteger totSections =[_sectionDataSource.sections count] ;
  3464. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3465. #if DEBUG
  3466. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:[NSString stringWithFormat:@"DEBUG [3] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section] delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3467. [alertView show];
  3468. #endif
  3469. return nil;
  3470. }
  3471. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3472. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3473. }
  3474. #pragma --------------------------------------------------------------------------------------------
  3475. #pragma mark - ==== Table ====
  3476. #pragma --------------------------------------------------------------------------------------------
  3477. - (void)tableViewSelect:(BOOL)edit
  3478. {
  3479. // chiudiamo eventuali swipe aperti
  3480. if (edit) [self.tableView setEditing:NO animated:NO];
  3481. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3482. [self.tableView setEditing:edit animated:YES];
  3483. _isSelectedMode = edit;
  3484. if (edit)
  3485. [self setUINavigationBarSelected];
  3486. else
  3487. [self setUINavigationBarDefault];
  3488. [self setTitle];
  3489. }
  3490. - (void)tableViewReload
  3491. {
  3492. // ricordiamoci le row selezionate
  3493. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3494. [self.tableView reloadData];
  3495. for (NSIndexPath *path in indexPaths)
  3496. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3497. [self setTableViewFooter];
  3498. if (self.tableView.editing)
  3499. [self setTitle];
  3500. }
  3501. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3502. {
  3503. return 60;
  3504. }
  3505. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3506. {
  3507. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3508. }
  3509. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3510. {
  3511. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3512. }
  3513. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3514. {
  3515. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3516. NSString *sectionTitle = [sections objectAtIndex:section];
  3517. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3518. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3519. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3520. return 20.f;
  3521. }
  3522. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3523. {
  3524. float shift;
  3525. UIVisualEffectView *visualEffectView;
  3526. // Titolo
  3527. NSString *titleSection;
  3528. // Controllo
  3529. if ([_sectionDataSource.sections count] == 0)
  3530. return nil;
  3531. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]]) titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3532. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]]) titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3533. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3534. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3535. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3536. else titleSection = NSLocalizedString(titleSection,nil);
  3537. // Formato titolo
  3538. NSString *currentDevice = [CCUtility currentDevice];
  3539. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3540. visualEffectView = [[UIVisualEffectView alloc] init];
  3541. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3542. } else {
  3543. UIVisualEffect *blurEffect;
  3544. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3545. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3546. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3547. }
  3548. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3549. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) shift = - 35;
  3550. else shift = - 20;
  3551. } else shift = - 10;
  3552. // Title
  3553. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3554. titleLabel.backgroundColor = [UIColor clearColor];
  3555. titleLabel.textColor = [UIColor blackColor];
  3556. titleLabel.font = [UIFont systemFontOfSize:12];
  3557. titleLabel.textAlignment = NSTextAlignmentLeft;
  3558. titleLabel.text = titleSection;
  3559. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3560. [visualEffectView addSubview:titleLabel];
  3561. // Elements
  3562. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3563. elementLabel.backgroundColor = [UIColor clearColor];
  3564. elementLabel.textColor = [UIColor blackColor];;
  3565. elementLabel.font = [UIFont systemFontOfSize:12];
  3566. elementLabel.textAlignment = NSTextAlignmentRight;
  3567. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3568. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3569. NSUInteger rowsCount = [metadatas count];
  3570. if (rowsCount == 0) return nil;
  3571. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3572. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3573. [visualEffectView addSubview:elementLabel];
  3574. return visualEffectView;
  3575. }
  3576. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3577. {
  3578. return [_sectionDataSource.sections indexOfObject:title];
  3579. }
  3580. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3581. {
  3582. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3583. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3584. else
  3585. return nil;
  3586. }
  3587. /*
  3588. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3589. {
  3590. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3591. }
  3592. }
  3593. */
  3594. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3595. {
  3596. NSString *typeCell;
  3597. NSString *dataFile;
  3598. NSString *lunghezzaFile;
  3599. CCMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3600. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  3601. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3602. else typeCell = @"CellMainTransfer";
  3603. if (!metadata)
  3604. return [tableView dequeueReusableCellWithIdentifier:typeCell];
  3605. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3606. // separator
  3607. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3608. // change color selection
  3609. UIView *selectionColor = [[UIView alloc] init];
  3610. selectionColor.backgroundColor = [NCBrandColor sharedInstance].selectBackgrond;
  3611. cell.selectedBackgroundView = selectionColor;
  3612. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3613. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3614. // ----------------------------------------------------------------------------------------------------------
  3615. // DEFAULT
  3616. // ----------------------------------------------------------------------------------------------------------
  3617. cell.fileImageView.image = nil;
  3618. cell.statusImageView.image = nil;
  3619. cell.offlineImageView.image = nil;
  3620. cell.synchronizedImageView.image = nil;
  3621. cell.sharedImageView.image = nil;
  3622. cell.labelTitle.enabled = YES;
  3623. cell.labelTitle.text = @"";
  3624. cell.labelInfoFile.enabled = YES;
  3625. cell.labelInfoFile.text = @"";
  3626. cell.progressView.progress = 0.0;
  3627. cell.progressView.hidden = YES;
  3628. cell.cancelTaskButton.hidden = YES;
  3629. cell.reloadTaskButton.hidden = YES;
  3630. cell.stopTaskButton.hidden = YES;
  3631. // Encrypted color
  3632. if (metadata.cryptated) {
  3633. cell.labelTitle.textColor = [NCBrandColor sharedInstance].cryptocloud;
  3634. } else {
  3635. cell.labelTitle.textColor = [UIColor blackColor];
  3636. }
  3637. // ----------------------------------------------------------------------------------------------------------
  3638. // File Name & Folder
  3639. // ----------------------------------------------------------------------------------------------------------
  3640. // nome del file
  3641. cell.labelTitle.text = metadata.fileNamePrint;
  3642. // è una directory
  3643. if (metadata.directory) {
  3644. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3645. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3646. lunghezzaFile = @" ";
  3647. // ----------------------------------------------------------------------------------------------------------
  3648. // Favorite Folder
  3649. // ----------------------------------------------------------------------------------------------------------
  3650. if (metadata.favorite) {
  3651. cell.offlineImageView.image = [UIImage imageNamed:image_favorite];
  3652. }
  3653. } else {
  3654. // File
  3655. dataFile = [CCUtility dateDiff:metadata.date];
  3656. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3657. // Plist ancora da scaricare
  3658. if (metadata.cryptated && [metadata.title length] == 0) {
  3659. dataFile = @" ";
  3660. lunghezzaFile = @" ";
  3661. }
  3662. TableLocalFile *recordLocalFile = [CCCoreData getLocalFileWithFileID:metadata.fileID activeAccount:app.activeAccount];
  3663. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3664. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3665. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3666. if ([metadata.type isEqualToString: k_metadataType_template] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO)
  3667. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", dataFile];
  3668. if ([metadata.type isEqualToString: k_metadataType_file] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO) {
  3669. if (recordLocalFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3670. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ • %@", dataFile, lunghezzaFile];
  3671. else
  3672. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ ◦ %@", dataFile, lunghezzaFile];
  3673. }
  3674. // Plist ancora da scaricare
  3675. if ([dataFile isEqualToString:@" "] && [lunghezzaFile isEqualToString:@" "])
  3676. cell.labelInfoFile.text = NSLocalizedString(@"_no_plist_pull_down_",nil);
  3677. cell.accessoryType = UITableViewCellAccessoryNone;
  3678. }
  3679. // ----------------------------------------------------------------------------------------------------------
  3680. // File Image View
  3681. // ----------------------------------------------------------------------------------------------------------
  3682. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3683. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3684. cell.fileImageView.image = [app.icoImagesCache objectForKey:metadata.fileID];
  3685. if (cell.fileImageView.image == nil) {
  3686. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  3687. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  3688. [app.icoImagesCache setObject:image forKey:metadata.fileID];
  3689. dispatch_async(dispatch_get_main_queue(), ^{
  3690. CCCellMainTransfer *cell = [tableView cellForRowAtIndexPath:indexPath];
  3691. if (cell)
  3692. cell.fileImageView.image = image;
  3693. });
  3694. });
  3695. }
  3696. } else {
  3697. if (metadata.directory)
  3698. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:metadata.iconName] color:[NCBrandColor sharedInstance].brand];
  3699. else
  3700. cell.fileImageView.image = [UIImage imageNamed:metadata.iconName];
  3701. if (metadata.thumbnailExists)
  3702. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3703. }
  3704. // ----------------------------------------------------------------------------------------------------------
  3705. // Image Status cyptated & Lock Passcode
  3706. // ----------------------------------------------------------------------------------------------------------
  3707. // File Cyptated
  3708. if (metadata.cryptated && metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_template] == NO) {
  3709. cell.statusImageView.image = [UIImage imageNamed:image_lock];
  3710. }
  3711. // Directory con passcode lock attivato
  3712. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileNameData];
  3713. if (metadata.directory && ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length]))
  3714. cell.statusImageView.image = [UIImage imageNamed:image_passcode];
  3715. // ----------------------------------------------------------------------------------------------------------
  3716. // Offline
  3717. // ----------------------------------------------------------------------------------------------------------
  3718. BOOL isOfflineFile = [CCCoreData isOfflineLocalFileID:metadata.fileID activeAccount:app.activeAccount];
  3719. if (isOfflineFile) {
  3720. cell.offlineImageView.image = [UIImage imageNamed:image_offline];
  3721. }
  3722. // ----------------------------------------------------------------------------------------------------------
  3723. // Favorite
  3724. // ----------------------------------------------------------------------------------------------------------
  3725. if (metadata.favorite) {
  3726. cell.offlineImageView.image = [UIImage imageNamed:image_favorite];
  3727. }
  3728. // ----------------------------------------------------------------------------------------------------------
  3729. // Share
  3730. // ----------------------------------------------------------------------------------------------------------
  3731. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3732. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3733. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3734. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3735. // Aggiungiamo il Tap per le shared
  3736. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3737. if (isShare) {
  3738. if (metadata.directory) {
  3739. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_folder_shared_with_me] color:[NCBrandColor sharedInstance].brand];
  3740. cell.sharedImageView.userInteractionEnabled = NO;
  3741. } else {
  3742. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetShare] color:[NCBrandColor sharedInstance].brand];
  3743. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3744. [tap setNumberOfTapsRequired:1];
  3745. cell.sharedImageView.userInteractionEnabled = YES;
  3746. [cell.sharedImageView addGestureRecognizer:tap];
  3747. }
  3748. }
  3749. if (isMounted) {
  3750. if (metadata.directory) {
  3751. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_folder_external] color:[NCBrandColor sharedInstance].brand];
  3752. cell.sharedImageView.userInteractionEnabled = NO;
  3753. } else {
  3754. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_shareMounted] color:[NCBrandColor sharedInstance].brand];
  3755. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3756. [tap setNumberOfTapsRequired:1];
  3757. cell.sharedImageView.userInteractionEnabled = YES;
  3758. [cell.sharedImageView addGestureRecognizer:tap];
  3759. }
  3760. }
  3761. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3762. if (metadata.directory) {
  3763. if ([shareLink length] > 0)
  3764. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_folder_public] color:[NCBrandColor sharedInstance].brand];
  3765. if ([shareUserAndGroup length] > 0)
  3766. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_folder_shared_with_me] color:[NCBrandColor sharedInstance].brand];
  3767. cell.sharedImageView.userInteractionEnabled = NO;
  3768. } else {
  3769. if ([shareLink length] > 0)
  3770. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_shareLink] color:[NCBrandColor sharedInstance].brand];
  3771. if ([shareUserAndGroup length] > 0)
  3772. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_actionSheetShare] color:[NCBrandColor sharedInstance].brand];
  3773. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3774. [tap setNumberOfTapsRequired:1];
  3775. cell.sharedImageView.userInteractionEnabled = YES;
  3776. [cell.sharedImageView addGestureRecognizer:tap];
  3777. }
  3778. }
  3779. } else {
  3780. cell.sharedImageView.userInteractionEnabled = NO;
  3781. }
  3782. // ----------------------------------------------------------------------------------------------------------
  3783. // downloadFile
  3784. // ----------------------------------------------------------------------------------------------------------
  3785. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3786. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:image_statusdownloadcrypto];
  3787. else cell.statusImageView.image = [UIImage imageNamed:image_statusdownload];
  3788. // sessionTaskIdentifier : RELOAD + STOP
  3789. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3790. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:image_stoptaskcrypto] forState:UIControlStateNormal];
  3791. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:image_stoptask] forState:UIControlStateNormal];
  3792. cell.cancelTaskButton.hidden = NO;
  3793. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtaskcrypto] forState:UIControlStateNormal];
  3794. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtask] forState:UIControlStateNormal];
  3795. cell.reloadTaskButton.hidden = NO;
  3796. }
  3797. // sessionTaskIdentifierPlist : RELOAD
  3798. if (metadata.sessionTaskIdentifierPlist != k_taskIdentifierDone) {
  3799. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtaskcrypto] forState:UIControlStateNormal];
  3800. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtask] forState:UIControlStateNormal];
  3801. cell.reloadTaskButton.hidden = NO;
  3802. }
  3803. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3804. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3805. if (progress > 0) {
  3806. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3807. else cell.progressView.progressTintColor = [UIColor blackColor];
  3808. cell.progressView.progress = progress;
  3809. cell.progressView.hidden = NO;
  3810. }
  3811. // ----------------------------------------------------------------------------------------------------------
  3812. // downloadFile Error
  3813. // ----------------------------------------------------------------------------------------------------------
  3814. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3815. cell.statusImageView.image = [UIImage imageNamed:image_statuserror];
  3816. if ([metadata.sessionError length] == 0)
  3817. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3818. else
  3819. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3820. }
  3821. }
  3822. // ----------------------------------------------------------------------------------------------------------
  3823. // uploadFile
  3824. // ----------------------------------------------------------------------------------------------------------
  3825. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3826. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:image_statusuploadcrypto];
  3827. else cell.statusImageView.image = [UIImage imageNamed:image_statusupload];
  3828. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:image_removetaskcrypto] forState:UIControlStateNormal];
  3829. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:image_removetask] forState:UIControlStateNormal];
  3830. cell.cancelTaskButton.hidden = NO;
  3831. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3832. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtaskcrypto] forState:UIControlStateNormal];
  3833. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:image_reloadtask] forState:UIControlStateNormal];
  3834. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:image_statusstopcrypto];
  3835. else cell.statusImageView.image = [UIImage imageNamed:image_statusstop];
  3836. cell.reloadTaskButton.hidden = NO;
  3837. cell.stopTaskButton.hidden = YES;
  3838. } else {
  3839. if (metadata.cryptated)[cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:image_stoptaskcrypto] forState:UIControlStateNormal];
  3840. else [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:image_stoptask] forState:UIControlStateNormal];
  3841. cell.stopTaskButton.hidden = NO;
  3842. cell.reloadTaskButton.hidden = YES;
  3843. }
  3844. // se non c'è una preview in bianconero metti l'immagine di default
  3845. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3846. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:image_uploaddisable] color:[NCBrandColor sharedInstance].brand];
  3847. cell.labelTitle.enabled = NO;
  3848. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3849. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3850. if (progress > 0) {
  3851. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3852. else cell.progressView.progressTintColor = [UIColor blackColor];
  3853. cell.progressView.progress = progress;
  3854. cell.progressView.hidden = NO;
  3855. }
  3856. // ----------------------------------------------------------------------------------------------------------
  3857. // uploadFileError
  3858. // ----------------------------------------------------------------------------------------------------------
  3859. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3860. cell.labelTitle.enabled = NO;
  3861. cell.statusImageView.image = [UIImage imageNamed:image_statuserror];
  3862. if ([metadata.sessionError length] == 0)
  3863. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3864. else
  3865. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3866. }
  3867. }
  3868. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3869. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3870. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3871. return cell;
  3872. }
  3873. - (void)setTableViewFooter
  3874. {
  3875. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3876. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3877. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3878. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3879. UIFont *appFont = [UIFont systemFontOfSize:12];
  3880. footerLabel.font = appFont;
  3881. footerLabel.textColor = [UIColor grayColor];
  3882. footerLabel.backgroundColor = [UIColor clearColor];
  3883. footerLabel.textAlignment = NSTextAlignmentCenter;
  3884. NSString *folders;
  3885. NSString *files;
  3886. NSString *footerText;
  3887. if (_sectionDataSource.directories > 1) {
  3888. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3889. } else if (_sectionDataSource.directories == 1){
  3890. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3891. } else {
  3892. folders = @"";
  3893. }
  3894. if (_sectionDataSource.files > 1) {
  3895. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3896. } else if (_sectionDataSource.files == 1){
  3897. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3898. } else {
  3899. files = @"";
  3900. }
  3901. if ([folders isEqualToString:@""]) {
  3902. footerText = files;
  3903. } else if ([files isEqualToString:@""]) {
  3904. footerText = folders;
  3905. } else {
  3906. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3907. }
  3908. footerLabel.text = footerText;
  3909. [footerView addSubview:footerLabel];
  3910. [self.tableView setTableFooterView:footerView];
  3911. }
  3912. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3913. {
  3914. NSString *textMessage;
  3915. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3916. // se non può essere selezionata deseleziona
  3917. if ([cell isEditing] == NO)
  3918. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3919. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3920. if (self.tableView.editing) {
  3921. [self setTitle];
  3922. return;
  3923. }
  3924. // test crash
  3925. NSArray *metadatas = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  3926. if (indexPath.row >= [metadatas count]) return;
  3927. // settiamo il record file.
  3928. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3929. //
  3930. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  3931. // se è in corso una sessione
  3932. if ([_metadata.session length] > 0) return;
  3933. if (_metadata.errorPasscode) {
  3934. // se UUID è nil lo sta ancora caricando quindi esci
  3935. if (!_metadata.uuid) return;
  3936. // esiste un hint ??
  3937. NSString *hint = [[CCCrypto sharedManager] getHintFromFile:_metadata.fileName isLocal:NO directoryUser:app.directoryUser];
  3938. // qui !! la richiesta della nuova passcode
  3939. if ([_metadata.uuid isEqualToString:[CCUtility getUUID]]) {
  3940. // stesso UUID ... la password è stata modificata !!!!!!
  3941. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_same_device_different_passcode_hint_",nil), hint];
  3942. else textMessage = NSLocalizedString(@"_same_device_different_passcode_", nil);
  3943. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3944. [alertView show];
  3945. } else {
  3946. // UUID diverso.
  3947. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_hint_",nil), _metadata.nameCurrentDevice, hint];
  3948. else textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_",nil), _metadata.nameCurrentDevice];
  3949. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3950. [alertView show];
  3951. }
  3952. // chiediamo la passcode e ricarichiamo tutto.
  3953. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3954. viewController.delegate = self;
  3955. viewController.fromType = CCBKPasscodeFromPasscode;
  3956. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3957. viewController.passcodeInputView.maximumLength = 64;
  3958. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3959. viewController.inputViewTitlePassword = NO;
  3960. viewController.title = k_brand;
  3961. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3962. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  3963. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3964. [self presentViewController:navigationController animated:YES completion:nil];
  3965. }
  3966. // modello o plist con il title a 0 allora è andato storto qualcosa ... ricaricalo
  3967. if (_metadata.cryptated && [_metadata.title length] == 0) {
  3968. NSString* selector;
  3969. if ([_metadata.type isEqualToString: k_metadataType_template]) selector = selectorLoadModelView;
  3970. else selector = selectorLoadPlist;
  3971. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3972. return;
  3973. }
  3974. // se il plist è caricato ed è un modello aprilo
  3975. if ([_metadata.type isEqualToString:k_metadataType_template]) [self openModel:_metadata.model isNew:false];
  3976. // file
  3977. if (_metadata.directory == NO && _metadata.errorPasscode == NO && [_metadata.type isEqualToString: k_metadataType_file]) {
  3978. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3979. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3980. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  3981. } else {
  3982. [[CCNetworking sharedNetworking] downloadFile:_metadata serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3983. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3984. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3985. }
  3986. }
  3987. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  3988. }
  3989. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3990. {
  3991. [self setTitle];
  3992. }
  3993. #pragma --------------------------------------------------------------------------------------------
  3994. #pragma mark ===== Synchronize Folder Cell =====
  3995. #pragma --------------------------------------------------------------------------------------------
  3996. - (void)synchronizeFolderGraphicsServerUrl:(NSString *)serverUrl animation:(BOOL)animation
  3997. {
  3998. BOOL cryptated = NO;
  3999. CCCellMain *cell;
  4000. for (NSString* fileID in _sectionDataSource.allRecordsDataSource) {
  4001. CCMetadata *recordMetadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  4002. if (recordMetadata.directory == NO)
  4003. continue;
  4004. if ([[CCUtility stringAppendServerUrl:_serverUrl addFileName:recordMetadata.fileNameData] isEqualToString:serverUrl]) {
  4005. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:recordMetadata.fileID];
  4006. cell = (CCCellMain *)[self.tableView cellForRowAtIndexPath:indexPath];
  4007. cryptated = recordMetadata.cryptated;
  4008. break;
  4009. }
  4010. }
  4011. if (!cell)
  4012. return;
  4013. if (animation) {
  4014. NSURL *myURL;
  4015. if (cryptated)
  4016. myURL = [[NSBundle mainBundle] URLForResource: @"synchronizedcrypto" withExtension:@"gif"];
  4017. else
  4018. myURL = [[NSBundle mainBundle] URLForResource: @"synchronized" withExtension:@"gif"];
  4019. } else {
  4020. cell.synchronizedImageView.image = nil;
  4021. }
  4022. }
  4023. #pragma --------------------------------------------------------------------------------------------
  4024. #pragma mark ===== Navigation ====
  4025. #pragma --------------------------------------------------------------------------------------------
  4026. - (BOOL)shouldPerformSegue
  4027. {
  4028. // if background return
  4029. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  4030. if (self.view.window == NO)
  4031. return NO;
  4032. // Collapsed ma siamo già in detail esci
  4033. if (self.splitViewController.isCollapsed)
  4034. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  4035. // Video in esecuzione esci
  4036. if (_detailViewController.photoBrowser.currentVideoPlayerViewController.isViewLoaded && _detailViewController.photoBrowser.currentVideoPlayerViewController.view.window) return NO;
  4037. return YES;
  4038. }
  4039. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  4040. {
  4041. id viewController = segue.destinationViewController;
  4042. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  4043. CCMetadata *metadata;
  4044. if ([viewController isKindOfClass:[UINavigationController class]]) {
  4045. UINavigationController *nav = viewController;
  4046. _detailViewController = (CCDetail *)nav.topViewController;
  4047. } else {
  4048. _detailViewController = segue.destinationViewController;
  4049. }
  4050. if ([sender isKindOfClass:[CCMetadata class]]) {
  4051. metadata = sender;
  4052. [allRecordsDataSourceImagesVideos addObject:sender];
  4053. } else {
  4054. metadata = _metadata;
  4055. for (NSString *fileID in _sectionDataSource.allFileID) {
  4056. CCMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  4057. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  4058. [allRecordsDataSourceImagesVideos addObject:metadata];
  4059. }
  4060. }
  4061. _detailViewController.metadataDetail = metadata;
  4062. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  4063. _detailViewController.dateFilterQuery = nil;
  4064. _detailViewController.isCameraUpload = NO;
  4065. [_detailViewController setTitle:metadata.fileNamePrint];
  4066. }
  4067. // can i go to next viewcontroller
  4068. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  4069. {
  4070. NSString *nomeDir;
  4071. if(self.tableView.editing == NO && _metadata.errorPasscode == NO){
  4072. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  4073. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  4074. // SE siamo in presenza di una directory bloccata E è attivo il block E la sessione password Lock è senza data ALLORA chiediamo la password per procedere
  4075. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  4076. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  4077. viewController.delegate = self;
  4078. viewController.fromType = CCBKPasscodeFromLockDirectory;
  4079. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  4080. viewController.inputViewTitlePassword = YES;
  4081. if ([CCUtility getSimplyBlockCode]) {
  4082. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  4083. viewController.passcodeInputView.maximumLength = 6;
  4084. } else {
  4085. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  4086. viewController.passcodeInputView.maximumLength = 64;
  4087. }
  4088. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  4089. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  4090. viewController.touchIDManager = touchIDManager;
  4091. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  4092. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  4093. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  4094. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  4095. [self presentViewController:navController animated:YES completion:nil];
  4096. return;
  4097. }
  4098. if (_metadata.cryptated) nomeDir = [_metadata.fileName substringToIndex:[_metadata.fileName length]-6];
  4099. else nomeDir = _metadata.fileName;
  4100. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  4101. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  4102. if (viewController.isViewLoaded == false) {
  4103. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  4104. viewController.isFolderEncrypted = _metadata.cryptated;
  4105. viewController.serverUrl = serverUrlPush;
  4106. viewController.titleMain = _metadata.fileNamePrint;
  4107. viewController.textBackButton = _titleMain;
  4108. // save self
  4109. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  4110. }
  4111. // OFF SearchBar
  4112. [viewController cancelSearchBar];
  4113. [self.navigationController pushViewController:viewController animated:YES];
  4114. }
  4115. }
  4116. @end