CCMain.m 250 KB

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