CCMain.m 255 KB

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