CCMain.m 248 KB

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