CCMain.m 253 KB

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