CCMain.m 248 KB

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